测试的代码连接上篇,更改上篇服务器端的代码,
package com.dasenlin.mutilatethreadchart;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
/**
* 服务端
* @author Administrator
*
*/
public class Server {
/**
* 多个客户端
*/
private List<MyChannal>all =new ArrayList<MyChannal>();
/**
* 启动服务器
* @param args
*/
public static void main(String[] args) {
try {
new Server().start();
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() throws IOException{
while(true){
ServerSocket server = new ServerSocket(9999);
while(true){
Socket client =server.accept();
MyChannal channel = new MyChannal(client);
all.add(channel);
new Thread(channel).start();
}
}
}
/**
* 一条线路
* @author Administrator
*
*/
private class MyChannal implements Runnable{
private DataInputStream dis;
private DataOutputStream dos;
private boolean isRunning =true;
public MyChannal(Socket client){
try {
dis = new DataInputStream(client.getInputStream());
dos = new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
IoCloserUtil.closeAll(dos,dis);
isRunning=false;
}
}
/**
* 接收消息
* @return
*/
private String receive(){
String msg="";
try {
msg = dis.readUTF();
} catch (IOException e) {
IoCloserUtil.closeAll(dis);
isRunning=false;
all.remove(this);
}
return msg;
}
/**
* 发送消息
* @param msg
*/
private void send(String msg){
if(null==msg||msg.equals(null)){
return ;
}
try {
dos.writeUTF(msg);
dos.flush();
} catch (IOException e) {
IoCloserUtil.closeAll(dos);
isRunning=false;
all.remove(this);
}
}
/**
* 发送给其他客户端
*/
private void sendOthers(){
String msg=this.receive();
for(MyChannal other :all){
if(other==this){
continue;
}
other.send(msg);
}
}
/**
* 循环运行,发送给其他客户端
*/
@Override
public void run() {
while(true){
sendOthers();
}
}
}
}