public class BioServer {
public static void main(String[] args) throws IOException {
ExecutorService threadPool = Executors.newCachedThreadPool();
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println(" 服务器启动");
while (true) {
final Socket socket = serverSocket.accept();
System.out.println("链接到一个客户端");
threadPool.execute(new Runnable() {
public void run() {
handler(socket);
}
});
}
}
private static void handler(Socket socket) {
try {
byte[] bytes = new byte[1024];
InputStream inputStream = socket.getInputStream();
while (true) {
int read = inputStream.read(bytes);
if (read == -1) break;
System.out.println(Thread.currentThread().getName() + ":" + new String(bytes, "gbk"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("关闭连接");
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
在cmd输入命令 telnet localhost 6666(这个是自己定义的端口号)
连接成功后如果要发送字符串则用按 Ctrl+] 即可