1. 什么是Socket?
Socket(套接字)是计算机网络中实现应用程序之间数据通信的一种方式。它为应用程序提供了发送和接收数据的接口。在Java中,java.net
包提供了Socket类和相关的类,用于实现网络编程。
2. 使用Socket建立TCP连接
在Java中,我们使用java.net.Socket
类和java.net.ServerSocket
类来实现基于TCP的客户端和服务器之间的通信。以下是一个简单的步骤:
ServerSocket
对象,指定监听的端口号。accept
方法等待客户端连接。Socket
对象,进行通信。Socket
对象,指定服务器的地址和端口号。Socket
对象的输入/输出流与服务器通信。3. Socket编程实例
下面是一个简单的客户端和服务器之间通信的示例。这个示例中,客户端向服务器发送一个字符串,服务器将字符串转换为大写并返回给客户端。
服务器端代码:
import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { public static void main(String[] args) { int port = 8080; try (ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("服务器启动,等待客户端连接..."); while (true) { Socket socket = serverSocket.accept(); new Thread(new ClientHandler(socket)).start(); } } catch (IOException e) { e.printStackTrace(); } } } class ClientHandler implements Runnable { private Socket socket; public ClientHandler(Socket socket) { this.socket = socket; } @Override public void run() { try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) { String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("客户端发送消息: " + inputLine); out.println(inputLine.toUpperCase()); } } catch (IOException e) { e.printStackTrace(); } } }
客户端代码:
import java.io.*; import java.net.Socket; public class TCPClient { public static void main(String[] args) { String host = "localhost"; int port = 8080; try (Socket socket = new Socket(host, port); 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("服务器响应: " + in.readLine()); } } catch (IOException e) { e.printStackTrace(); } } }
4. 使用DatagramSocket进行UDP编程
与基于TCP的Socket编程不同,UDP编程使用java.net.DatagramSocket
类和java.net.DatagramPacket
类来实现数据报文的发送和接收。
以下是一个简单的UDP编程示例,客户端向服务器发送一个字符串,服务器将字符串转换为大写并返回给客户端。
服务器端代码:
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UDPServer { public static void main(String[] args) { int port = 8080; try (DatagramSocket socket = new DatagramSocket(port)) { byte[] buf = new byte[256]; DatagramPacket packet = new DatagramPacket(buf, buf.length); System.out.println("服务器启动,等待客户端发送数据..."); while (true) { socket.receive(packet); String received = new String(packet.getData(), 0, packet.getLength()); System.out.println("客户端发送消息: " + received); String response = received.toUpperCase(); byte[] responseBytes = response.getBytes(); InetAddress address = packet.getAddress(); int clientPort = packet.getPort(); DatagramPacket responsePacket = new DatagramPacket(responseBytes, responseBytes.length, address, clientPort); socket.send(responsePacket); } } catch (IOException e) { e.printStackTrace(); } } }
客户端代码:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UDPClient { public static void main(String[] args) { String host = "localhost"; int port = 8080; try (DatagramSocket socket = new DatagramSocket(); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) { InetAddress address = InetAddress.getByName(host); String userInput; while ((userInput = stdIn.readLine()) != null) { byte[] buf = userInput.getBytes(); DatagramPacket requestPacket = new DatagramPacket(buf, buf.length, address, port); socket.send(requestPacket); byte[] responseBuf = new byte[256]; DatagramPacket responsePacket = new DatagramPacket(responseBuf, responseBuf.length); socket.receive(responsePacket); String response = new String(responseBuf, 0, responsePacket.getLength()); System.out.println("服务器响应: " + response); } } catch (IOException e) { e.printStackTrace(); } } }
通过上述示例,我们完成了一个基于TCP和UDP的客户端和服务器之间的简单通信。希望这些示例可以帮助您更好地理解Java Socket编程。请注意,这些示例仅用于教学目的,在实际应用中,您可能需要考虑诸如异常处理、超时控制、多线程和资源管理等其他因素。