java写一个socket server端代码
时间: 2023-08-10 22:05:43 浏览: 92
socket服务器端编程
下面是一个简单的Java Socket Server端代码示例:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
public static void main(String[] args) throws IOException {
// 创建一个ServerSocket对象,监听指定端口号
int port = 8888;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server started on port " + port);
// 循环监听客户端连接
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected: " + socket.getInetAddress().getHostAddress());
// 处理客户端请求
new Thread(() -> {
try {
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
// 读取客户端发送的数据
byte[] buffer = new byte[1024];
int length = inputStream.read(buffer);
String request = new String(buffer, 0, length);
System.out.println("Client request: " + request);
// 向客户端发送响应数据
String response = "Hello, client!";
outputStream.write(response.getBytes());
outputStream.flush();
// 关闭流和连接
inputStream.close();
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
}
```
该代码通过创建一个ServerSocket对象监听指定端口,然后通过循环监听客户端的连接,处理客户端请求,最后关闭连接。在处理客户端请求时,使用了多线程的方式,可以同时处理多个客户端的请求。
阅读全文