用Java socket 实现客户端与服务器之间的数据的发送与接受。。。双向的

用Java socket 实现客户端与服务器之间的数据的发送与接受。。。双向的,第1张

下面是一个简单的通讯实例,进行Server和Client之间的文件传输。。如果是简单的文本传输的话简化掉文本操作的内容即可。。

1服务器

package sterning;

import javaioBufferedInputStream;

import javaioDataInputStream;

import javaioDataOutputStream;

import javaioFile;

import javaioFileInputStream;

import javanetServerSocket;

import javanetSocket;

public class ServerTest {

int port = 8821;

void start() {

Socket s = null;

try {

ServerSocket ss = new ServerSocket(port);

while (true) {

// 选择进行传输的文件

String filePath = "D:\\librar";

File fi = new File(filePath);

Systemoutprintln("文件长度:" + (int) filength());

// public Socket accept() throws

// IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。

s = ssaccept();

Systemoutprintln("建立socket链接");

DataInputStream dis = new DataInputStream(new BufferedInputStream(sgetInputStream()));

disreadByte();

DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));

DataOutputStream ps = new DataOutputStream(sgetOutputStream());

//将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java 4th里有现成的代码。

pswriteUTF(figetName());

psflush();

pswriteLong((long) filength());

psflush();

int bufferSize = 8192;

byte[] buf = new byte[bufferSize];

while (true) {

int read = 0;

if (fis != null) {

read = fisread(buf);

}

if (read == -1) {

break;

}

pswrite(buf, 0, read);

}

psflush();

// 注意关闭socket链接哦,不然客户端会等待server的数据过来,

// 直到socket超时,导致数据不完整。

fisclose();

sclose();

Systemoutprintln("文件传输完成");

}

} catch (Exception e) {

eprintStackTrace();

}

}

public static void main(String arg[]) {

new ServerTest()start();

}

}

2socket的Util辅助类

package sterning;

import javanet;

import javaio;

public class ClientSocket {

private String ip;

private int port;

private Socket socket = null;

DataOutputStream out = null;

DataInputStream getMessageStream = null;

public ClientSocket(String ip, int port) {

thisip = ip;

thisport = port;

}

/ //

创建socket连接

@throws Exception

exception

/

public void CreateConnection() throws Exception {

try {

socket = new Socket(ip, port);

} catch (Exception e) {

eprintStackTrace();

if (socket != null)

socketclose();

throw e;

} finally {

}

}

public void sendMessage(String sendMessage) throws Exception {

try {

out = new DataOutputStream(socketgetOutputStream());

if (sendMessageequals("Windows")) {

outwriteByte(0x1);

outflush();

return;

}

if (sendMessageequals("Unix")) {

outwriteByte(0x2);

outflush();

return;

}

if (sendMessageequals("Linux")) {

outwriteByte(0x3);

outflush();

} else {

outwriteUTF(sendMessage);

outflush();

}

} catch (Exception e) {

eprintStackTrace();

if (out != null)

outclose();

throw e;

} finally {

}

}

public DataInputStream getMessageStream() throws Exception {

try {

getMessageStream = new DataInputStream(new BufferedInputStream(socketgetInputStream()));

return getMessageStream;

} catch (Exception e) {

eprintStackTrace();

if (getMessageStream != null)

getMessageStreamclose();

throw e;

} finally {

}

}

public void shutDownConnection() {

try {

if (out != null)

outclose();

if (getMessageStream != null)

getMessageStreamclose();

if (socket != null)

socketclose();

} catch (Exception e) {

}

}

}

3客户端

package sterning;

import javaioBufferedOutputStream;

import javaioDataInputStream;

import javaioDataOutputStream;

import javaioFileOutputStream;

public class ClientTest {

private ClientSocket cs = null;

private String ip = "localhost";// 设置成服务器IP

private int port = 8821;

private String sendMessage = "Windwos";

public ClientTest() {

try {

if (createConnection()) {

sendMessage();

getMessage();

}

} catch (Exception ex) {

exprintStackTrace();

}

}

private boolean createConnection() {

cs = new ClientSocket(ip, port);

try {

csCreateConnection();

Systemoutprint("连接服务器成功!" + "\n");

return true;

} catch (Exception e) {

Systemoutprint("连接服务器失败!" + "\n");

return false;

}

}

private void sendMessage() {

if (cs == null)

return;

try {

cssendMessage(sendMessage);

} catch (Exception e) {

Systemoutprint("发送消息失败!" + "\n");

}

}

private void getMessage() {

if (cs == null)

return;

DataInputStream inputStream = null;

try {

inputStream = csgetMessageStream();

} catch (Exception e) {

Systemoutprint("接收消息缓存错误\n");

return;

}

try {

//本地保存路径,文件名会自动从服务器端继承而来。

String savePath = "E:\\";

int bufferSize = 8192;

byte[] buf = new byte[bufferSize];

int passedlen = 0;

long len=0;

savePath += inputStreamreadUTF();

DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(newBufferedOutputStream(new FileOutputStream(savePath))));

len = inputStreamreadLong();

Systemoutprintln("文件的长度为:" + len + "\n");

Systemoutprintln("开始接收文件!" + "\n");

while (true) {

int read = 0;

if (inputStream != null) {

read = inputStreamread(buf);

}

passedlen += read;

if (read == -1) {

break;

}

//下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比

Systemoutprintln("文件接收了" + (passedlen 100/ len) + "%\n");

fileOutwrite(buf, 0, read);

}

Systemoutprintln("接收完成,文件存为" + savePath + "\n");

fileOutclose();

} catch (Exception e) {

Systemoutprintln("接收消息错误" + "\n");

return;

}

}

public static void main(String arg[]) {

new ClientTest();

}

}

服务器端源码:

import javaioBufferedReader;

import javaioFile;

import javaioFileNotFoundException;

import javaioFileOutputStream;

import javaioIOException;

import javaioInputStream;

import javaioInputStreamReader;

import javanetServerSocket;

import javanetSocket;

/

文件名:ServerReceivejava

实现功能:作为服务器接收客户端发送的文件

具体实现过程:

1、建立SocketServer,等待客户端的连接

2、当有客户端连接的时候,按照双方的约定,这时要读取一行数据

其中保存客户端要发送的文件名和文件大小信息

3、根据文件名在本地创建文件,并建立好流通信

4、循环接收数据包,将数据包写入文件

5、当接收数据的长度等于提前文件发过来的文件长度,即表示文件接收完毕,关闭文件

6、文件接收工作结束

public class ServerReceive {

public static void main(String[] args) {

/与服务器建立连接的通信句柄/

ServerSocket ss = null;

Socket s = null;

/定义用于在接收后在本地创建的文件对象和文件输出流对象/

File file = null;

FileOutputStream fos = null;

/定义输入流,使用socket的inputStream对数据包进行输入/

InputStream is = null;

/定义byte数组来作为数据包的存储数据包/

byte[] buffer = new byte[4096 5];

/用来接收文件发送请求的字符串/

String comm = null;

/建立socekt通信,等待服务器进行连接/

try {

ss = new ServerSocket(4004);

s = ssaccept();

} catch (IOException e) {

eprintStackTrace();

}

/读取一行客户端发送过来的约定信息/

try {

InputStreamReader isr = new InputStreamReader(sgetInputStream());

BufferedReader br = new BufferedReader(isr);

comm = brreadLine();

} catch (IOException e) {

Systemoutprintln("服务器与客户端断开连接");

}

/开始解析客户端发送过来的请求命令/

int index = commindexOf("/#");

/判断协议是否为发送文件的协议/

String xieyi = commsubstring(0, index);

if(!xieyiequals("111")){

Systemoutprintln("服务器收到的协议码不正确");

return;

}

/解析出文件的名字和大小/

comm = commsubstring(index + 2);

index = commindexOf("/#");

String filename = commsubstring(0, index)trim();

String filesize = commsubstring(index + 2)trim();

/创建空文件,用来进行接收文件/

file = new File(filename);

if(!fileexists()){

try {

filecreateNewFile();

} catch (IOException e) {

Systemoutprintln("服务器端创建文件失败");

}

}else{

/在此也可以询问是否覆盖/

Systemoutprintln("本路径已存在相同文件,进行覆盖");

}

/以上就是客户端代码中写到的服务器的准备部分/

/

服务器接收文件的关键代码/

try {

/将文件包装到文件输出流对象中/

fos = new FileOutputStream(file);

long file_size = LongparseLong(filesize);

is = sgetInputStream();

/size为每次接收数据包的长度/

int size = 0;

/count用来记录已接收到文件的长度/

long count = 0;

/使用while循环接收数据包/

while(count < file_size){

/从输入流中读取一个数据包/

size = isread(buffer);

/将刚刚读取的数据包写到本地文件中去/

foswrite(buffer, 0, size);

fosflush();

/将已接收到文件的长度+size/

count += size;

Systemoutprintln("服务器端接收到数据包,大小为" + size);

}

} catch (FileNotFoundException e) {

Systemoutprintln("服务器写文件失败");

} catch (IOException e) {

Systemoutprintln("服务器:客户端断开连接");

}finally{

/

将打开的文件关闭

如有需要,也可以在此关闭socket连接

/

try {

if(fos != null)

fosclose();

} catch (IOException e) {

eprintStackTrace();

}//catch (IOException e)

}//finally

}//public static void main(String[] args)

}//public class ServerReceive

客户端源码:

import javaioFile;

import javaioFileInputStream;

import javaioFileNotFoundException;

import javaioIOException;

import javaioOutputStream;

import javaioPrintStream;

import javanetSocket;

/

文件名:ClientSendjava

实现功能:作为客户端向服务器发送一个文件

具体实现过程:

1、建立与服务器端的连接,IP:127001, port:4004

2、将文件的名字和大小通过自定义的文件传输协议,发送到服务器

3、循环读取本地文件,将文件打包发送到数据输出流中

4、关闭文件,结束传输

/

public class ClientSend {

public static void main(String[] args) {

/与服务器建立连接的通信句柄/

Socket s = null;

/定义文件对象,即为要发送的文件

如果使用绝对路径,不要忘记使用'/'和'\'的区别

具体区别,请读者自行查询

/

File sendfile = new File("APICHM");

/定义文件输入流,用来打开、读取即将要发送的文件/

FileInputStream fis = null;

/定义byte数组来作为数据包的存储数据包/

byte[] buffer = new byte[4096 5];

/定义输出流,使用socket的outputStream对数据包进行输出/

OutputStream os = null;

/检查要发送的文件是否存在/

if(!sendfileexists()){

Systemoutprintln("客户端:要发送的文件不存在");

return;

}

/与服务器建立连接/

try {

s = new Socket("127001", 4004);

}catch (IOException e) {

Systemoutprintln("未连接到服务器");

}

/用文件对象初始化fis对象

以便于可以提取出文件的大小

/

try {

fis = new FileInputStream(sendfile);

} catch (FileNotFoundException e1) {

e1printStackTrace();

}

/首先先向服务器发送关于文件的信息,以便于服务器进行接收的相关准备工作

具体的准备工作,请查看服务器代码。

发送的内容包括:发送文件协议码(此处为111)/#文件名(带后缀名)/#文件大小

/

try {

PrintStream ps = new PrintStream(sgetOutputStream());

psprintln("111/#" + sendfilegetName() + "/#" + fisavailable());

psflush();

} catch (IOException e) {

Systemoutprintln("服务器连接中断");

}

/

此处睡眠2s,等待服务器把相关的工作准备好

也是为了保证网络的延迟

读者可自行选择添加此代码

/

try {

Threadsleep(2000);

} catch (InterruptedException e1) {

e1printStackTrace();

}

/之前的准备工作结束之后

下面就是文件传输的关键代码

/

try {

/获取socket的OutputStream,以便向其中写入数据包/

os = sgetOutputStream();

/ size 用来记录每次读取文件的大小/

int size = 0;

/使用while循环读取文件,直到文件读取结束/

while((size = fisread(buffer)) != -1){

Systemoutprintln("客户端发送数据包,大小为" + size);

/向输出流中写入刚刚读到的数据包/

oswrite(buffer, 0, size);

/刷新一下/

osflush();

}

} catch (FileNotFoundException e) {

Systemoutprintln("客户端读取文件出错");

} catch (IOException e) {

Systemoutprintln("客户端输出文件出错");

}finally{

/

将打开的文件关闭

如有需要,也可以在此关闭socket连接

/

try {

if(fis != null)

fisclose();

} catch (IOException e) {

Systemoutprintln("客户端文件关闭出错");

}//catch (IOException e)

}//finally

}//public static void main(String[] args)

}//public class ClientSend

服务器告知双方对方的ip地址,并协调由哪一方主动连接。

如 协调结果是: 把c2的地址告诉c1,让c1主动连接c2,让c2打开端口等待连接。

要考虑认证问题,比如c2如何知道连接上来的是c1,而不是其他人,就需要有认证机制。

另外要考虑内网问题。由于从外部连接内网里面的IP地址是相当繁琐复杂的,所以需要特别的机制处理。

写个简单点的服务器跟客服端就行了我写了个很简单的,只能在一个客户端跟一个服务器通信,在控制台输入下面这个是服务器import javaio;

import javanet;

import javautilScanner;public class Server

{

public static void main(String[] args)

{

try {

ServerSocket server=new ServerSocket(8888);//定义客户端的端口号

Socket client=serveraccept();//定义一个Socket对象

InputStream is=clientgetInputStream();//服务器接受信息输入流,也就是接受从服务器段发送过来的消息

BufferedReader br=new BufferedReader(new InputStreamReader(is));//用bufferedreader包装下输入流

OutputStream os=clientgetOutputStream();//这是用来给服务器发送消息的输出流

PrintStream ps=new PrintStream(os);

Scanner scanner=new Scanner(Systemin);//从键盘输入字符串

boolean flag=true;//定义一个死循环,让服务器不停的接受从客户端发送来的字符串

while(flag)

{

String s=brreadLine();//s是从客户端接受到得字符串

Systemoutprintln(s);

String s2=scannernextLine();//s2是写给客户端的字符串

psprintln(s2); //给客户端发送你写的东西

}

clientclose();

} catch (IOException e) {//try 跟catch你不用管,这是用来处理异常的,就是固定格式

eprintStackTrace();

}

}

} 下面是客户端import javaio;

import javanet;

import javautilScanner;public class Client

{ public static void main(String[] args)

{

try

{

Socket client=new Socket("192168----",8888);//IP地址是个字符串,端口号是个整数,这个端口号要跟前面你写的那个一样,还有IP地址,写你的机器的IP地址

InputStream is=clientgetInputStream();//这边的两个流跟上面服务器的差不多的作用

BufferedReader bf=new BufferedReader(new InputStreamReader(is));

OutputStream os=clientgetOutputStream();

PrintStream ps=new PrintStream(os);

Scanner scanner=new Scanner(Systemin);

boolean flag=true;

while(flag)//这句话可以让客户端不停的说话

{

String s2=scannernextLine();

psprintln(s2);

String s=bfreadLine();

Systemoutprintln(s); }

clientclose();

}

catch (UnknownHostException e)

{

eprintStackTrace();

}

catch (IOException e)

{

eprintStackTrace();

} }}

可以用TCP或UDP协议。两者不同之处在于,TCP要建立服务器客户端必须和服务器连接,才能和其他客户进行联系。

但UDF不需要,只要知道对方的IP和端口,就可以连接任何一台客户端。

想这样类似QQ的代码很多,晚上搜一下就有。这里给一个客户端和服务器。

-------------------

import javaawt;

import javaawtevent;

import javanet;

import javaio;

import javautilloggingLevel;

import javautilloggingLogger;

class myframe extends Frame implements ActionListener,WindowListener,Runnable,KeyListener

{

Thread mythread = new Thread(this);

Socket mysocket;

DataInputStream in;

DataOutputStream out;

Label label_ip = new Label("IP");

Label label_port = new Label("Port");

TextField text_ip = new TextField("127110",15);

TextField text_port = new TextField("8888",15);

Button button_connect = new Button("连接");

TextArea text_area_show = new TextArea();

TextField text_send = new TextField(45);

Button button_send = new Button("发送");

myframe()

{

Panel panel1 = new Panel();

Panel panel2 = new Panel();

panel1setLayout(new FlowLayout());

panel1add(label_ip);

panel1add(text_ip);

panel1add(label_port);

panel1add(text_port);

panel1add(button_connect);

panel2setLayout(new FlowLayout());

panel2add(text_send);

panel2add(button_send);

add(panel1,BorderLayoutNORTH);

add(text_area_show,BorderLayoutCENTER);

add(panel2,BorderLayoutSOUTH);

text_sendaddKeyListener(this);

button_connectaddActionListener(this);

button_sendaddActionListener(this);

addWindowListener(this);

thissetTitle("客户端");

setBounds(200,200,400,350);

setVisible(true);

}

public void actionPerformed(ActionEvent e)

{

if(egetSource() == button_connect)

{

try

{

String ip = null,port = null;

ip = text_ipgetText();

port = text_portgetText();

mysocket = new Socket(ip, IntegerparseInt(port));

in = new DataInputStream(mysocketgetInputStream());

out = new DataOutputStream(mysocketgetOutputStream());

}

catch (UnknownHostException ex)

{

LoggergetLogger(myframeclassgetName())log(LevelSEVERE, null, ex);

}

catch (IOException ex)

{

LoggergetLogger(myframeclassgetName())log(LevelSEVERE, null, ex);

}

mythreadstart();

}

if(egetSource() == button_send)

{

if(mysocketisConnected() == true)

{

String temp = null;

temp = text_sendgetText();

try

{

outwriteUTF(temp);

text_sendsetText(null);

}

catch (IOException ex)

{

LoggergetLogger(myframeclassgetName())log(LevelSEVERE, null, ex);

}

}

}

}

public void run()

{

while(true)

{

String temp = null;

try

{

temp = inreadUTF();

}

catch (IOException ex)

{

text_area_showappend("服务器退出\n");

return;

}

temp += "\n";

text_area_showappend(temp);

}

}

public void keyPressed(KeyEvent e)

{

if(egetKeyCode() == KeyEventVK_ENTER)

{

String temp = null;

temp = text_sendgetText();

try

{

outwriteUTF(temp);

}

catch (IOException ex)

{

LoggergetLogger(myframeclassgetName())log(LevelSEVERE, null, ex);

}

}

}

public void windowClosing(WindowEvent e)

{

Systemexit(0);

}

public void windowOpened(WindowEvent e) {}

public void windowClosed(WindowEvent e) {}

public void windowIconified(WindowEvent e) {}

public void windowDeiconified(WindowEvent e) {}

public void windowActivated(WindowEvent e) {}

public void windowDeactivated(WindowEvent e) {}

public void keyTyped(KeyEvent e) {}

public void keyReleased(KeyEvent e) {}

}

public class mywindow

{

public static void main(String argv[])

{

myframe f = new myframe();

}

}

--------------------------------

import javaawteventWindowAdapter;

import javaawteventWindowEvent;

import javaioDataInputStream;

import javaioDataOutputStream;

import javaioIOException;

import javanetServerSocket;

import javanetSocket;

import javautilLinkedList;

import javautilloggingLevel;

import javautilloggingLogger;

import javaxswingJTextArea;

class RecvMegSock extends Thread

{

LinkedList SocketList = null;

Socket ClientSock = null;

JTextArea jTextArea1;

RecvMegSock(LinkedList list,Socket s,JTextArea t)

{

SocketList = list;

jTextArea1 = t;

ClientSock = s;

start();

}

public void run()

{

while(true)

{

try

{

DataInputStream in = new DataInputStream(ClientSockgetInputStream());

String word = inreadUTF();

jTextArea1setText(jTextArea1getText() + word + "\n");

for(int i = 0;i < SocketListsize();i++)

{

Socket s = (Socket)SocketListget(i);

DataOutputStream out = new DataOutputStream(sgetOutputStream());

outwriteUTF(word);

}

}

catch (IOException ex)

{

for(int i = 0;i < SocketListsize();i++)

{

Socket s = (Socket)SocketListget(i);

if(s == ClientSock)

SocketListremove(s);

}

for(int i = 0;i < SocketListsize();i++)

{

Socket s = (Socket)SocketListget(i);

try

{

DataOutputStream out = new DataOutputStream(sgetOutputStream());

outwriteUTF(ClientSockgetInetAddress() + "已经退出!!\n");

}

catch (IOException ex1)

{

LoggergetLogger(RecvMegSockclassgetName())log(LevelSEVERE, null, ex1);

}

}

jTextArea1setText(jTextArea1getText() + ClientSockgetInetAddress() + "已经退出!!" + "\n");

return;

}

}

}

}

class AcceptSockThread extends Thread

{

ServerSocket ServerSock = null;

LinkedList SocketList = null;

JTextArea TextArea;

AcceptSockThread(ServerSocket s,LinkedList list,JTextArea t)

{

ServerSock = s;

SocketList = list;

TextArea = t;

start();

}

public void run()

{

while(true)

{

Socket ClientSock = null;

try

{

boolean same = false;

ClientSock = ServerSockaccept(); /

for(int i = 0;i < SocketListsize();i++)

{

Socket s = (Socket)SocketListget(i);

if(sgetInetAddress()equals(ClientSockgetInetAddress()) && sgetPort() == ClientSockgetPort())

{

DataOutputStream out = new DataOutputStream(sgetOutputStream());

outwriteUTF(ClientSockgetInetAddress() + "你已经连接了服务器!!\n");

same = true;

}

}

if(same == true)

continue;

/

new RecvMegSock(SocketList,ClientSock,TextArea);

SocketListadd(ClientSock);

for(int i = 0;i < SocketListsize();i++)

{

Socket s = (Socket)SocketListget(i);

DataOutputStream out = new DataOutputStream(sgetOutputStream());

outwriteUTF(ClientSockgetInetAddress() + "成功连接服务器\n");

}

TextAreasetText(TextAreagetText() + ClientSockgetInetAddress() + "连接到服务器\n");

}

catch (IOException ex)

{

LoggergetLogger(AcceptSockThreadclassgetName())log(LevelSEVERE, null, ex);

}

}

}

}

public class ServerDialog extends javaxswingJDialog

{

ServerSocket Server = null;

LinkedList SocketList = null;

public ServerDialog(javaawtFrame parent, boolean modal)

{

super(parent, modal);

initComponents();

try

{

Server = new ServerSocket(8888);

SocketList = new LinkedList();

new AcceptSockThread(Server,SocketList,jTextArea1);

}

catch (IOException ex)

{

LoggergetLogger(ServerDialogclassgetName())log(LevelSEVERE, null, ex);

}

}

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents

private void initComponents() {

jScrollPane1 = new javaxswingJScrollPane();

jTextArea1 = new javaxswingJTextArea();

jTextField1 = new javaxswingJTextField();

jButton1 = new javaxswingJButton();

setDefaultCloseOperation(javaxswingWindowConstantsDISPOSE_ON_CLOSE);

getContentPane()setLayout(null);

jTextArea1setColumns(20);

jTextArea1setEditable(false);

jTextArea1setRows(5);

jScrollPane1setViewportView(jTextArea1);

getContentPane()add(jScrollPane1);

jScrollPane1setBounds(10, 10, 380, 250);

getContentPane()add(jTextField1);

jTextField1setBounds(10, 270, 290, 21);

jButton1setText("发送");

jButton1addActionListener(new javaawteventActionListener() {

public void actionPerformed(javaawteventActionEvent evt) {

jButton1ActionPerformed(evt);

}

});

getContentPane()add(jButton1);

jButton1setBounds(310, 270, 80, 25);

pack();

}// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(javaawteventActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

if(SocketListsize() == 0)

{

jTextArea1setText(jTextArea1getText() + "没有人连接!!" + "\n");

return;

}

for(int i = 0;i < SocketListsize();i++)

{

DataOutputStream out;

try

{

out = new DataOutputStream(((Socket) SocketListget(i))getOutputStream());

if(jTextField1getText() != null)

outwriteUTF(jTextField1getText());

}

catch (IOException ex)

{

LoggergetLogger(ServerDialogclassgetName())log(LevelSEVERE, null, ex);

}

}

jTextArea1setText(jTextArea1getText() + jTextField1getText() + "\n");

}//GEN-LAST:event_jButton1ActionPerformed

public static void main(String args[])

{

ServerDialog dlg = new ServerDialog(null,true);

dlgsetBounds(300, 200, 400, 325);

dlgaddWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

Systemexit(0);

}

});

dlgsetVisible(true);

}

// Variables declaration - do not modify//GEN-BEGIN:variables

private javaxswingJButton jButton1;

private javaxswingJScrollPane jScrollPane1;

private javaxswingJTextArea jTextArea1;

private javaxswingJTextField jTextField1;

// End of variables declaration//GEN-END:variables

}

SocketClient1java内容如下:

package compolyphyllasocket;

import javaioBufferedReader;

import javaioIOException;

import javaioInputStreamReader;

import javaioPrintWriter;

import javanetSocket;

import javanetUnknownHostException;

public class SocketClient1 {

private Socket socket;

public SocketClient1() {

try {

socket = new Socket("127001", 2222);

} catch (UnknownHostException e) {

eprintStackTrace();

} catch (IOException e) {

eprintStackTrace();

}

}

/

@param args

/

public static void main(String[] args) {

new SocketClient1()startClient();

}

public void startClient() {

new Thread(new ClientReader(socket))start();

new Thread(new ClientWriter(socket))start();

}

}

class ClientReader implements Runnable {

private Socket socket;

public ClientReader(Socket socket) {

thissocket = socket;

}

public void run() {

BufferedReader br = getReader();

String msg = null;

try {

while ((msg = brreadLine()) != null) {

Systemoutprintln("client:" + msg);

}

} catch (IOException e) {

eprintStackTrace();

} finally {

try {

if (br != null)

brclose();

if (socket != null)

socketclose();

} catch (IOException e) {

// TODO Auto-generated catch block

eprintStackTrace();

}

}

}

private BufferedReader getReader() {

try {

return new BufferedReader(new InputStreamReader(socket

getInputStream()));

} catch (IOException e) {

eprintStackTrace();

}

return null;

}

}

class ClientWriter implements Runnable {

private Socket socket;

public ClientWriter(Socket socket) {

thissocket = socket;

}

public void run() {

PrintWriter pw = getWriter();

BufferedReader br = new BufferedReader(new InputStreamReader(Systemin));

String str = null;

try {

while ((str = brreadLine()) != null) {

pwprintln(str);

pwflush();

}

} catch (IOException e) {

eprintStackTrace();

} finally {

if (pw != null)

pwclose();

try {

if (socket != null)

socketclose();

} catch (IOException e) {

// TODO Auto-generated catch block

eprintStackTrace();

}

}

}

private PrintWriter getWriter() {

try {

return new PrintWriter(socketgetOutputStream());

} catch (IOException e) {

eprintStackTrace();

}

return null;

}

}

SocketServer1java内容如下:

package compolyphyllasocket;

import javaioBufferedReader;

import javaioIOException;

import javaioInputStreamReader;

import javaioPrintWriter;

import javanetServerSocket;

import javanetSocket;

public class SocketServer1 {

private ServerSocket ss;

public SocketServer1() {

try {

ss = new ServerSocket(2222);

} catch (IOException e) {

eprintStackTrace();

}

}

public static void main(String[] args) {

new SocketServer1()startServer();

}

public void startServer() {

try {

while (true) {

Socket s = ssaccept();

new Thread(new ServerReader(s))start();

new Thread(new ServerWriter(s))start();

}

} catch (IOException e) {

eprintStackTrace();

}

}

}

class ServerReader implements Runnable {

private Socket socket;

public ServerReader(Socket socket) {

thissocket = socket;

}

public void run() {

BufferedReader br = getReader();

String msg = null;

try {

while((msg = brreadLine()) != null) {

Systemoutprintln("server:" + msg);

}

} catch (IOException e) {

eprintStackTrace();

} finally {

try {

if(br != null)

brclose();

if(socket != null)

socketclose();

} catch (IOException e) {

// TODO Auto-generated catch block

eprintStackTrace();

}

}

}

private BufferedReader getReader() {

try {

return new BufferedReader(new InputStreamReader(socketgetInputStream()));

} catch (IOException e) {

eprintStackTrace();

}

return null;

}

}

class ServerWriter implements Runnable {

private Socket socket;

public ServerWriter(Socket socket) {

thissocket = socket;

}

public void run() {

PrintWriter pw = getWriter();

BufferedReader br = new BufferedReader(new InputStreamReader(Systemin));

String str = null;

try {

while((str = brreadLine()) != null) {

pwprintln(str);

pwflush();

}

} catch (IOException e) {

eprintStackTrace();

} finally {

if (pw != null)

pwclose();

try {

if (socket != null)

socketclose();

} catch (IOException e) {

// TODO Auto-generated catch block

eprintStackTrace();

}

}

}

private PrintWriter getWriter() {

try {

return new PrintWriter(socketgetOutputStream());

} catch (IOException e) {

eprintStackTrace();

}

return null;

}

}

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
网站模板库 » 用Java socket 实现客户端与服务器之间的数据的发送与接受。。。双向的

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情