请写出简单的java socket通信代码
时间: 2023-05-14 22:05:31 浏览: 96
简单的socket通信代码
当然可以,以下是一个简单的 Java Socket 通信代码示例:
Server 端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server started, waiting for client...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Client: " + inputLine);
out.println("Server: " + inputLine);
}
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
}
```
Client 端代码:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888);
System.out.println("Connected to server: " + socket.getInetAddress().getHostAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("Server: " + in.readLine());
}
in.close();
out.close();
stdIn.close();
socket.close();
}
}
```
这个示例中,Server 端监听 8888 端口,等待客户端连接。客户端连接后,Server 端通过 BufferedReader 和 PrintWriter 分别获取输入流和输出流,然后通过 while 循环不断读取客户端发送的消息,并将消息原样返回给客户端。
Client 端连接到 Server 端的 8888 端口,同样通过 BufferedReader 和 PrintWriter 分别获取输入流和输出流,然后通过 while 循环不断读取用户输入的消息,并将消息发送给 Server 端,然后等待 Server 端返回的消息并打印出来。
这样就实现了一个简单的 Java Socket 通信。
阅读全文