- 每个请求都需要创建独立的线程,与对应客户端进行数据的读写。
- 当并发量大时,需要创建大量的线程来处理链接,系统资源占用比较大。
- 当建立连接后,如果当前的线程暂时没有数据可以可读,则线程就会阻塞在Read上,造成资源浪费。
ps:在cmd中使用telnet 127.0.0.1 6666链接上服务器后,按住ctrl+] 即可开始向服务器传递信息,每次固定为 send+字符串。
package com.stu.bio;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BioServer {
public static void main(String[] args) throws IOException {
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
//创建一个serverSocket
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("服务器启动了");
while (true) {
//主线程会在这一直等待
final Socket socket = serverSocket.accept();
System.out.println("有一个线程链接进来了");
//创建一个线程与之通讯
newCachedThreadPool.execute(new Runnable() {
public void run() {
//与客户端通讯
handle(socket);
}
});
}
}
/**
* 编写一个方法与客户端通讯
*/
public static void handle(Socket socket) {
Thread thread = Thread.currentThread();
System.out.println("thread id::" + thread.getId() + "----thread name::" + thread.getName());
try {
byte[] bytes = new byte[1024];
InputStream inputStream = socket.getInputStream();
while (true) {
//子线程会在这里一直等待
int length = inputStream.read(bytes);
if (length != -1) {
//输出客户端发出的数据
System.out.println(new String(bytes, 0, length));
} else {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}