在Java中,我们通常使用java.net包下的Socket类(对于TCP)和DatagramSocket类(对于UDP)来实现TCP和UDP的通信。以下是简单的示例代码。
TCP客户端
java
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 12345); // 连接到服务器的IP和端口
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("Hello from TCP Client!");
String response = in.readLine();
System.out.println("Server response: " + response);
socket.close();
}
}
TCP服务器
java
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(12345); // 监听指定的端口
Socket clientSocket = serverSocket.accept(); // 等待客户端连接
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("Received from client: " + inputLine);
out.println("Hello from TCP Server!");
if ("exit".equalsIgnoreCase(inputLine)) {
break;
}
}
clientSocket.close();
serverSocket.close();
}
}
UDP客户端
java
import java.io.*;
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
InetAddress ipAddress = InetAddress.getByName("localhost");
byte[] sendData = "Hello from UDP Client!".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, 12345);
socket.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("UDP server says: " + message);
socket.close();
}
}
UDP服务器
java
import java.io.*;
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(12345);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("UDP client says: " + message);
InetAddress ipAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
byte[] sendData = "Hello from UDP Server!".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, port);
socket.send(sendPacket);
socket.close();
}
}
请注意,以上代码示例仅用于演示目的,并未包含错误处理和异常处理。在实际应用中,您应该添加适当的错误处理和异常处理来确保代码的健壮性。