掌握Java Socket编程:网络通信技巧解析
发表时间: 2023-11-11 13:59
hello宝子们...艾斯视觉擅长ui设计和前端开发10年+经验!努力做好每一份选择我们的信任!希望宝子们捧个人场!需要的宝子可以关注私信排期哈!致敬感谢感恩!
Java Socket编程是通过使用Java的Socket类和ServerSocket类来实现网络通信的方法。下面是一个简单的示例,演示了如何使用Java Socket编程来实现客户端和服务器端之间的通信。
import java.io.*;import java.net.*;public class Server { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(12345); System.out.println("Server is running and waiting for client to connect..."); Socket clientSocket = serverSocket.accept(); System.out.println("Client connected."); 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 received: " + inputLine); } in.close(); out.close(); clientSocket.close(); serverSocket.close(); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } }}
```
import java.io.*;import java.net.*;public class Client { public static void main(String[] args) { try { Socket socket = new Socket("localhost", 12345); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in)); String userInputLine; while ((userInputLine = userInput.readLine()) != null) { out.println(userInputLine); System.out.println("Server: " + in.readLine()); } out.close(); in.close(); userInput.close(); socket.close(); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } }}
```
在上面的示例中,服务器端通过ServerSocket监听指定端口,当客户端连接时,接受连接并创建输入输出流。客户端通过Socket连接到服务器端,并创建输入输出流进行通信。这样就实现了简单的网络通信。