java socket 代码
时间: 2023-07-30 15:06:29 浏览: 73
java socket 源码
以下是一个简单的 Java Socket 通信示例代码,其中实现了客户端和服务端之间的简单文本通信:
服务端代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888); // 创建一个ServerSocket,监听8888端口
System.out.println("Server is started, waiting for client to connect...");
Socket socket = serverSocket.accept(); // 等待客户端连接
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (true) {
String message = in.readLine(); // 读取客户端发送的消息
System.out.println("Received message from client: " + message);
out.println("Server received message: " + message); // 发送响应消息给客户端
}
} 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) {
try {
Socket socket = new Socket("localhost", 8888); // 创建一个Socket,连接到服务端的8888端口
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String message = reader.readLine(); // 从控制台读取用户输入的消息
out.println(message); // 发送消息给服务端
String response = in.readLine(); // 读取服务端的响应消息
System.out.println("Received response from server: " + response); // 输出响应消息
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个简单的示例实现了客户端和服务端之间的文本通信,可以通过修改代码实现更复杂的网络通信需求。
阅读全文