Socket 简介与 Java Socket 编程示例
import java.io.*;
import java.net.*;
public class SimpleChat {
public static void main(String[] args) {
try {
// 创建服务器端Socket,监听9999端口
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务器启动,等待客户端连接...");
// 无限循环,持续监听客户端连接请求
while (true) {
// 调用accept()方法开始监听,等待客户端连接
Socket clientSocket = serverSocket.accept();
System.out.println("客户端连接成功!");
// 创建一个新的线程处理与客户端的通信
Thread t = new Thread(new ServerThread(clientSocket));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThread implements Runnable {
private Socket clientSocket;
private BufferedReader reader;
private PrintWriter writer;
public ServerThread(Socket clientSocket) throws IOException {
this.clientSocket = clientSocket;
InputStreamReader isReader = new InputStreamReader(clientSocket.getInputStream());
reader = new BufferedReader(isReader);
writer = new PrintWriter(clientSocket.getOutputStream(), true);
}
public void run() {
try {
while (true) {
String message = reader.readLine();
System.out.println("收到消息:" + message);
writer.println("消息已接收,内容是:" + message);
if (message.equals("bye")) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
writer.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
这段代码是一个简单的服务器端程序,使用Java Socket编程实现了一个基于TCP协议的简单聊天服务器。它创建了一个ServerSocket来监听9999端口,并接受来自客户端的连接请求。每当有新的客户端连接时,它就会创建一个新的线程来处理与该客户端的通信。代码中使用了PrintWriter和BufferedReader来读写数据,并对可能发生的异常进行了处理。
评论已关闭