java socket测试
时间: 2024-01-14 12:03:38 浏览: 158
以下是一个简单的Java Socket测试的例子:
1.服务端代码:
```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(8888);
System.out.println("服务端已启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端已连接,客户端地址:" + socket.getInetAddress().getHostAddress());
socket.close();
serverSocket.close();
}
}
```
2.客户端代码:
```java
import java.io.IOException;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888);
System.out.println("客户端已连接到服务端,服务端地址:" + socket.getInetAddress().getHostAddress());
socket.close();
}
}
```
阅读全文