在Java中,可以通过Socket类和ServerSocket类来实现socket通信。以下是一个简单的示例代码:
- 创建ServerSocket并监听指定端口:
ServerSocket serverSocket = new ServerSocket(8888); Socket socket = serverSocket.accept();
- 创建Socket并连接到服务器端口:
Socket socket = new Socket("localhost", 8888);
- 获取输入流和输出流进行通信:
// 服务端获取输入流 InputStream inputStream = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String message = reader.readLine(); // 服务端发送消息 OutputStream outputStream = socket.getOutputStream(); PrintWriter writer = new PrintWriter(outputStream, true); writer.println("Hello, client!"); // 客户端获取输入流 InputStream inputStream = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String message = reader.readLine(); // 客户端发送消息 OutputStream outputStream = socket.getOutputStream(); PrintWriter writer = new PrintWriter(outputStream, true); writer.println("Hello, server!");
以上是一个简单的socket通信示例,通过这种方式可以实现客户端和服务端之间的通信。在实际开发中,可以根据具体需求更进一步的封装和优化。