Java 并发TCP 服务器[CODE]

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ThreadServer {

public static void main(String args[]){
ServerSocket server = null;
Socket client = null;
try{
server = new ServerSocket(9999);
while(true){
System.out.println("等待客户端的连接~~~");
client = server.accept();
new Thread(new ThreadServerHandler(client)).start();
}

} catch(Exception e){

}

}
}

class ThreadServerHandler implements Runnable{
private Socket client = null;
public ThreadServerHandler(Socket client){
this.client = client;
}

public void run(){
String buf = null;
BufferedReader in = null;
PrintStream out = null;
try{
in = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
out = new PrintStream(this.client.getOutputStream());
while(true){
buf = in.readLine();
if("bye".equals(buf)){
break;
} else {
System.out.println("Recv:"+buf);
out.println("Echo: " + buf);
}
}

this.client.close();

} catch (Exception e){

}
}
}
posted @ 2012-03-23 09:04  hnrainll  阅读(761)  评论(0编辑  收藏  举报