Socket网络通信之线程池

public static void main(String[] args) throws IOException {
System.out.println("tcp协议服务器端启动..");
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();//线程池
// 创建服务器端连接
ServerSocket serverSocket = new ServerSocket(8080);
try {
while (true) {
// 接受客户端请求? 阻塞功能
Socket accept = serverSocket.accept();
newCachedThreadPool.execute(new Runnable(){

@Override
public void run() {
try {
InputStream inputStream = accept.getInputStream();
// 将字节流转换成String类型
byte[] bytes = new byte[1024];
int len = inputStream.read(bytes);
String result=new String(bytes,0,len);
System.out.println("服务器端接受客户端内端?:"+result);
OutputStream outputStream = accept.getOutputStream();
outputStream.write("我是曹操哦.getBytes());
} catch (Exception e) {
// TODO: handle exception
}

}
});

}
} catch (Exception e) {
// TODO: handle exception
}finally {
serverSocket.close();
}

}

}

客户端

public static void main(String[] args) throws IOException {
System.out.println("socket tcp客户端启成功?....");
//创建socket客户端?
Socket socket=new Socket("127.0.0.1",8080);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("我是曹操".getBytes());
socket.close();
}

猜你喜欢

转载自www.cnblogs.com/nancheng/p/9232489.html