java代码实现socket做服务端接收报文,并返回响应报文
时间: 2023-05-11 14:05:58 浏览: 662
利用socket连续发送与连续接收数据
5星 · 资源好评率100%
可以使用以下代码实现socket做服务端接收报文,并返回响应报文:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server started.");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected: " + socket.getInetAddress().getHostAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received message: " + inputLine);
out.println("Response message: " + inputLine);
}
in.close();
out.close();
socket.close();
}
}
}
```
这段代码会监听12345端口,当有客户端连接时,会打印客户端的IP地址。然后会读取客户端发送的消息,并返回相同的消息。当客户端关闭连接时,服务端也会关闭连接。
阅读全文