检测Socket和ServerSocket双向连接成功示例
时间: 2023-12-07 08:15:40 浏览: 108
以下是一个基本的Java示例代码,用于检测Socket和ServerSocket的双向连接是否成功:
Server端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("Server is running, waiting for client connection...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected!");
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String message = in.readLine();
System.out.println("Client: " + message);
out.write("Hello from server!");
out.newLine();
out.flush();
in.close();
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
Client端代码:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 9999);
System.out.println("Connected to server!");
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.write("Hello from client!");
out.newLine();
out.flush();
String message = in.readLine();
System.out.println("Server: " + message);
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
运行Server代码后,它将在本地监听9999端口,并等待客户端连接。运行Client代码后,它将尝试连接到本地的9999端口。如果一切正常,客户端将发送消息“Hello from client!”,并在控制台上显示来自服务器的响应“Hello from server!”。这表明Socket和ServerSocket的双向连接成功。
阅读全文