最近在学java,感觉比起c++的TCP通信要简单多了呀
package my_network_test.zuse;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.*;
public class EchoServer {
private ServerSocketChannel serverSocketChannel;
private ExecutorService executorService; //线程池
private final int POOL_SIZE=4; //单CPU工作时线程的数量
public EchoServer() throws IOException {
//serverSocket=new ServerSocket(port);
serverSocketChannel=ServerSocketChannel.open();
serverSocketChannel.socket().setReuseAddress(true);
int port = 4444;
serverSocketChannel.socket().bind(new InetSocketAddress(port)); //把服务器进程与一个本地端口绑定
//创建线程池
executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);
System.out.println("服务器启动...");
}
public void service(){
while(true){
SocketChannel socket;
try{
socket=serverSocketChannel.accept();
executorService.execute(new Handle(socket));
}catch (IOException e){
e.printStackTrace();
}
}
}
static public void main(String[] args) throws IOException{
new EchoServer().service();
}
}
class Handle implements Runnable{
private final SocketChannel socketChannel;
private Socket socket;
public Handle(SocketChannel socketChannel){
this.socketChannel=socketChannel;
}
public void run(){
try{
socket=socketChannel.socket(); //获得与socketChannel关联的Socket对象
System.out.println("建立新连接:"+socket.getInetAddress()+":"+socket.getPort());
BufferedReader brSocket=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
String msg;
while((msg=brSocket.readLine())!=null){
if(msg.equals("end")) {
System.out.println("客户端"+socket.getPort()+"已断开连接");
break;
}
System.out.println("来自客户端"+socket.getPort()+":"+msg);
pw.println("服务器收到!");
}
}catch (IOException e){
System.out.println("客户端"+socket.getPort()+"已断开连接");
}finally {
try{
if(socket!=null) socket.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}