用Java 编写一个基于socket的简易聊天程序。所编写的程序应具有如下功能: 1.具有点对点通信功能,任意客户端之间能够发送消息; 2.具有群组通信功能,客户端能够向组内成员同时发送消息,其他组成员不能收到; 3.具有广播功能,客户端能够向所有其他成员广播消息
时间: 2024-02-06 15:11:12 浏览: 299
基于socket 的JAVA聊天程序
好的,下面是代码实现:
1. 建立服务端
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务端已启动,等待客户端连接...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("客户端已连接,IP地址为:" + socket.getInetAddress());
// 创建线程处理客户端请求
ServerThread serverThread = new ServerThread(socket);
serverThread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThread extends Thread {
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while (true) {
String message = reader.readLine();
if (message == null) {
continue;
}
// 广播消息
if (message.equals("broadcast")) {
String broadcastMessage = reader.readLine();
broadcast(socket, broadcastMessage);
}
// 群组消息
else if (message.equals("group")) {
String groupName = reader.readLine();
String groupMessage = reader.readLine();
group(groupName, socket, groupMessage);
}
// 点对点消息
else {
String toUser = message;
String privateMessage = reader.readLine();
toUser(toUser, socket, privateMessage);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 广播消息
private void broadcast(Socket fromSocket, String message) throws IOException {
for (Socket socket : ServerUtils.getSockets()) {
if (socket != fromSocket) {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("广播消息:" + message + "\n");
writer.flush();
}
}
}
// 群组消息
private void group(String groupName, Socket fromSocket, String message) throws IOException {
for (Socket socket : ServerUtils.getGroupSockets(groupName)) {
if (socket != fromSocket) {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("群组消息:" + message + "\n");
writer.flush();
}
}
}
// 点对点消息
private void toUser(String toUser, Socket fromSocket, String message) throws IOException {
Socket toSocket = ServerUtils.getSocket(toUser);
if (toSocket != null) {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(toSocket.getOutputStream()));
writer.write("点对点消息:" + message + "\n");
writer.flush();
} else {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fromSocket.getOutputStream()));
writer.write("用户不存在\n");
writer.flush();
}
}
}
```
2. 建立客户端
```java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
private static Socket socket;
public static void main(String[] args) {
try {
socket = new Socket("localhost", 8888);
// 创建线程接收服务端消息
ClientThread clientThread = new ClientThread(socket);
clientThread.start();
// 输入用户名
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入用户名:");
String username = reader.readLine();
// 循环发送消息
while (true) {
System.out.println("请输入指令(1.点对点消息 2.群组消息 3.广播消息):");
int command = Integer.parseInt(reader.readLine());
switch (command) {
// 点对点消息
case 1:
System.out.print("请输入要发送的用户名:");
String toUser = reader.readLine();
System.out.print("请输入要发送的消息:");
String privateMessage = reader.readLine();
sendPrivateMessage(toUser, privateMessage, username);
break;
// 群组消息
case 2:
System.out.print("请输入要发送的组名:");
String groupName = reader.readLine();
System.out.print("请输入要发送的消息:");
String groupMessage = reader.readLine();
sendGroupMessage(groupName, groupMessage, username);
break;
// 广播消息
case 3:
System.out.print("请输入要发送的消息:");
String broadcastMessage = reader.readLine();
sendBroadcastMessage(broadcastMessage, username);
break;
default:
System.out.println("无效指令");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 发送点对点消息
private static void sendPrivateMessage(String toUser, String message, String fromUser) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write(toUser + "\n");
writer.write(message + "\n");
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response = reader.readLine();
System.out.println(response);
}
// 发送群组消息
private static void sendGroupMessage(String groupName, String message, String fromUser) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("group\n");
writer.write(groupName + "\n");
writer.write(message + "\n");
writer.flush();
}
// 发送广播消息
private static void sendBroadcastMessage(String message, String fromUser) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("broadcast\n");
writer.write(message + "\n");
writer.flush();
}
}
class ClientThread extends Thread {
private Socket socket;
public ClientThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String message = reader.readLine();
if (message == null) {
continue;
}
System.out.println(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
3. 工具类
```java
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ServerUtils {
private static Map<String, Socket> userSocketMap = new HashMap<>();
private static Map<String, List<Socket>> groupSocketMap = new HashMap<>();
// 添加用户
public static void addUser(String username, Socket socket) {
userSocketMap.put(username, socket);
}
// 获取用户socket
public static Socket getSocket(String username) {
return userSocketMap.get(username);
}
// 添加群组
public static void addGroup(String groupName, Socket socket) {
if (groupSocketMap.containsKey(groupName)) {
groupSocketMap.get(groupName).add(socket);
} else {
List<Socket> sockets = new ArrayList<>();
sockets.add(socket);
groupSocketMap.put(groupName, sockets);
}
}
// 获取群组socket列表
public static List<Socket> getGroupSockets(String groupName) {
return groupSocketMap.get(groupName);
}
// 获取所有socket
public static List<Socket> getSockets() {
List<Socket> sockets = new ArrayList<>(userSocketMap.values());
sockets.addAll(getAllGroupSockets());
return sockets;
}
// 获取所有群组socket
private static List<Socket> getAllGroupSockets() {
List<Socket> sockets = new ArrayList<>();
for (List<Socket> list : groupSocketMap.values()) {
sockets.addAll(list);
}
return sockets;
}
}
```
以上就是基于socket的简易聊天程序的Java代码实现。其中,通过ServerUtils类实现了用户和群组的管理,ServerThread类处理客户端请求,ClientThread类接收服务端消息,Client类完成客户端的发送消息操作。此程序仅为简单示例,实际应用中需要考虑更多的异常情况和安全问题。
阅读全文