1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
public static void main(String[] args) { try(ServerSocket server = new ServerSocket(8080)){ System.out.println("正在等待客户端连接..."); Socket socket = server.accept(); System.out.println("客户端已连接,IP地址为:"+socket.getInetAddress().getHostAddress()); }catch (IOException e){ e.printStackTrace(); } }
创建客户端:
```java
public static void main(String[] args) { try (Socket socket = new Socket("localhost", 8080)){ System.out.println("已连接到服务端!"); }catch (IOException e){ System.out.println("服务端连接失败!"); e.printStackTrace(); } }
|