JavaTCP协议实现一对一聊天与UDP协议实现群聊案例
1.TCP协议实现一对一聊天
1.1服务端运行结果
1.2客服端运行结果
1.3代码汇总
服务端
package twentyone;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(12345); // 使用端口12345
System.out.println("等待客户端连接...");
Socket clientSocket = serverSocket.accept(); // 等待客户端连接
System.out.println("客户端已连接");
// 获取输入输出流
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
// 读取客户端消息并回复
String clientMessage;
while ((clientMessage = in.readLine()) != null) {
System.out.println("张超(客户端): " + clientMessage);
// 从控制台读取服务器消息并发送给客户端
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
System.out.print(" 蒂蒂(服务器): ");
String serverMessage = consoleReader.readLine();
out.println(serverMessage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端
package twentyone;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 12345); // 连接服务器
// 获取输入输出流
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// 从控制台读取客户端消息并发送给服务器
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
String clientMessage;
while (true) {
System.out.print("张超(客户端): ");
clientMessage = consoleReader.readLine();
out.println(clientMessage);
// 读取服务器消息并打印
String serverMessage = in.readLine();
System.out.println("蒂蒂(服务器)" + serverMessage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.UDP协议实现群聊
2.1服务端运行结果
2.2客户端运行结果
2.3代码汇总
第一服务端
package twentyone;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPServer {
public static void main(String[] args) {
try {
DatagramSocket serverSocket = new DatagramSocket(12345);
System.out.println("第一个服务器已启动,等待客户端加入...");
while (true) {
byte[] receiveData = new byte[1024];
// 接收客户端消息
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String clientMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("第一个服务器收到来自 " + receivePacket.getAddress() + ":" + receivePacket.getPort() + " 的消息: " + clientMessage);
// 广播消息给其他客户端
broadcastMessage(serverSocket, clientMessage, receivePacket.getAddress(), receivePacket.getPort());
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void broadcastMessage(DatagramSocket serverSocket, String message, InetAddress excludeAddress, int excludePort) {
try {
byte[] sendData = message.getBytes();
// 获取广播地址
InetAddress broadcastAddress = InetAddress.getByName("255.255.255.255");
int broadcastPort = 12345;
// 广播消息给所有客户端,除了发起广播的客户端
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcastAddress, broadcastPort);
serverSocket.send(sendPacket);
} catch (Exception e) {
e.printStackTrace();
}
}
}
第二服务端
package twentyone;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class SecondUDPServer {
public static void main(String[] args) {
try {
DatagramSocket serverSocket = new DatagramSocket(12346);
System.out.println("第二个服务器已启动,等待客户端加入...");
while (true) {
byte[] receiveData = new byte[1024];
// 接收客户端消息
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String clientMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("第二个服务器收到来自 " + receivePacket.getAddress() + ":" + receivePacket.getPort() + " 的消息: " + clientMessage);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端
package twentyone;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
class ConsoleHelper {
private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
public static String readLine(String prompt) {
try {
System.out.print(prompt);
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException("Error reading from console", e);
}
}
}
public class UDPClient {
public static void main(String[] args) {
try {
DatagramSocket clientSocket = new DatagramSocket(); // 随机分配端口
// 启动接收线程
new Thread(() -> receiveMessages(clientSocket, 3)).start();
while (true) {
// 从控制台读取消息并发送给服务端1和服务端2
String message = ConsoleHelper.readLine("客户端: ");
byte[] sendData = message.getBytes();
// 发送消息给服务端1
DatagramPacket sendPacket1 = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("localhost"), 12345);
clientSocket.send(sendPacket1);
// 发送消息给服务端2
DatagramPacket sendPacket2 = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("localhost"), 12346);
clientSocket.send(sendPacket2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void receiveMessages(DatagramSocket clientSocket, int maxReceiveCount) {
try {
byte[] receiveData = new byte[1024];
int receiveCount = 0;
while (receiveCount < maxReceiveCount) {
// 接收服务器广播消息
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String serverMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("服务器: " + serverMessage);
receiveCount++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}