写一段java代码,实现socket功能
时间: 2023-08-12 08:12:53 浏览: 92
以下是一个简单的 Java Socket 例子,实现了客户端与服务端之间的通信:
服务端代码:
```java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(12345); // 创建服务器端 Socket,监听端口为 12345
System.out.println("Server started.");
while (true) {
Socket socket = serverSocket.accept(); // 等待客户端连接
System.out.println("Client connected.");
new Thread(new ServerHandler(socket)).start(); // 创建新的线程处理客户端请求
}
}
}
```
服务端处理器代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerHandler implements Runnable {
private Socket socket;
public ServerHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 获取输入流
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); // 获取输出流
String message = in.readLine(); // 读取客户端发送的消息
System.out.println("Received message: " + message);
out.println("Message received."); // 回复客户端
socket.close(); // 关闭连接
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 12345); // 创建客户端 Socket,连接到服务器端口 12345
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 获取输入流
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); // 获取输出流
out.println("Hello, server!"); // 向服务端发送消息
String message = in.readLine(); // 读取服务端回复的消息
System.out.println("Received message: " + message);
socket.close(); // 关闭连接
}
}
```
这个例子创建了一个简单的 Socket 通信程序,服务端监听端口 12345,客户端连接到该端口并向服务端发送消息。服务端接收到消息后回复客户端。
阅读全文