java服务端客户端代码 java服务端客户端代码是多少( 四 )


ServerReaderWriter c = new ServerReaderWriter(ss);//建立客服端
System.out.println("第" + i + "个客服端启动!");
++i;
new Thread(c).start();//启动线程
clients.add(c);
}
} catch (EOFException e) {
System.out.println("客服端被关闭!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerReaderWriter implements Runnable {//建议使用Runnable避免你重写run方法麻烦!
private Socket s;
private DataInputStream dis = null;//注意赋值,养成好习惯!
private DataOutputStream dos = null;
private boolean bConnected = false;//用于调用连接成功后的run方法
public ServerReaderWriter(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("有客户退出!");
}
}
public void run() {
try {
while (bConnected) {
String input = dis.readUTF();
System.out.println(input);
for(int i=0; iclients.size(); ++i) {
ServerReaderWriter c = clients.get(i);
c.send(input);
}
}
} catch(SocketException e) {
System.out.println("一个客服端已关闭,请勿再像他发送信息!");
} catch (EOFException e) {
System.out.println("谢谢使用!");
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dis != null) {
dis.close();
}
if (dos != null) {
dos.close();
}
if (s != null) {
s.close();
s = null;
}
//clients.clear();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
Client端代码:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class TestClient extends Frame { //用到Frame生产界面比较直观
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
TextField tfText = new TextField();
TextArea taContent = new TextArea();
Thread tRecv = new Thread(new ClientReaderWriter());
public static void main(String[] args){
new TestClient().launchFrame();
}
public void launchFrame() {
this.setSize(300, 300); //设置客服端窗口格式
this.setLocation(400, 300);
add(tfText, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
this.pack();
this.addWindowListener(new WindowAdapter() { //监听窗口关闭事件
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfText.addActionListener(new TFListener());
setVisible(true);
connect();
tRecv.start();
}
public void connect() {
try {
s = new Socket("127.0.0.1", 5050); //依据自己的服务器,我这里用的localhost
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("连接服务器!");
bConnected = true;
} catch(ConnectException e) {
System.out.println("请检查服务器是否启动!");
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.exit(0);
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();

推荐阅读