用Java实现以下内容1.利用Socket通信机制实现一种即时通信系统。 2.系统分为服务端和客户端两部分: 2.1 客户端向服务器注册自己的信息,包括IP地址、端口号、用户名等; 2.2 客户端启动后向服务器查询其它用户在线状态,包括用户名、IP地址、端口号等; 2.3 客户端之间通过服务器实现信息交换; 2.4 服务器端维护用户的状态信息,对用户查询做出响应,并实现消息转发;
时间: 2024-04-15 08:28:34 浏览: 118
以下是用Java实现的即时通信系统的代码示例:
服务端:
```java
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class Server {
private static final int PORT = 8080;
private Map<String, ClientInfo> clients;
public Server() {
clients = new HashMap<>();
}
public void start() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server started on port " + PORT + "...");
while (true) {
Socket clientSocket = serverSocket.accept();
new ClientHandler(clientSocket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class ClientHandler extends Thread {
private Socket clientSocket;
private ObjectInputStream inputStream;
private ObjectOutputStream outputStream;
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
public void run() {
try {
inputStream = new ObjectInputStream(clientSocket.getInputStream());
outputStream = new ObjectOutputStream(clientSocket.getOutputStream());
while (true) {
Message message = (Message) inputStream.readObject();
switch (message.getType()) {
case REGISTER:
handleRegister(message);
break;
case QUERY:
handleQuery(message);
break;
case MESSAGE:
handleMessage(message);
break;
}
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
if (outputStream != null)
outputStream.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void handleRegister(Message message) throws IOException {
String username = message.getUsername();
String ipAddress = message.getIpAddress();
int port = message.getPort();
ClientInfo clientInfo = new ClientInfo(username, ipAddress, port);
clients.put(username, clientInfo);
System.out.println("Registered new client: " + username);
}
private void handleQuery(Message message) throws IOException {
String queryUsername = message.getUsername();
Message response = new Message(MessageType.RESPONSE);
for (ClientInfo client : clients.values()) {
if (!client.getUsername().equals(queryUsername)) {
response.addUser(client.getUsername(), client.getIpAddress(), client.getPort());
}
}
outputStream.writeObject(response);
}
private void handleMessage(Message message) throws IOException {
String recipient = message.getRecipient();
ClientInfo client = clients.get(recipient);
if (client != null) {
Socket recipientSocket = new Socket(client.getIpAddress(), client.getPort());
ObjectOutputStream recipientOutputStream = new ObjectOutputStream(recipientSocket.getOutputStream());
recipientOutputStream.writeObject(message);
recipientOutputStream.close();
recipientSocket.close();
}
}
}
public static void main(String[] args) {
Server server = new Server();
server.start();
}
}
class ClientInfo {
private String username;
private String ipAddress;
private int port;
public ClientInfo(String username, String ipAddress, int port) {
this.username = username;
this.ipAddress = ipAddress;
this.port = port;
}
public String getUsername() {
return username;
}
public String getIpAddress() {
return ipAddress;
}
public int getPort() {
return port;
}
}
```
客户端:
```java
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private static final String SERVER_IP = "127.0.0.1";
private static final int SERVER_PORT = 8080;
public static void main(String[] args) {
try {
Socket socket = new Socket(SERVER_IP, SERVER_PORT);
System.out.println("Connected to server...");
ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your username: ");
String username = scanner.nextLine();
System.out.print("Enter your IP address: ");
String ipAddress = scanner.nextLine();
System.out.print("Enter your port number: ");
int port = scanner.nextInt();
Message registerMessage = new Message(MessageType.REGISTER);
registerMessage.setUsername(username);
registerMessage.setIpAddress(ipAddress);
registerMessage.setPort(port);
outputStream.writeObject(registerMessage);
new Thread(() -> {
while (true) {
try {
Message response = (Message) inputStream.readObject();
if (response.getType() == MessageType.RESPONSE) {
System.out.println("Online users:");
for (UserInfo user : response.getUsers()) {
System.out.println(user.getUsername() + " - " + user.getIpAddress() + ":" + user.getPort());
}
System.out.println();
} else if (response.getType() == MessageType.MESSAGE) {
System.out.println("Received message from " + response.getSender() + ": " + response.getContent());
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}).start();
while (true) {
System.out.print("Enter a command (query/send): ");
String command = scanner.next();
if (command.equals("query")) {
Message queryMessage = new Message(MessageType.QUERY);
queryMessage.setUsername(username);
outputStream.writeObject(queryMessage);
} else if (command.equals("send")) {
System.out.print("Enter the recipient's username: ");
String recipient = scanner.next();
scanner.nextLine(); // Consume the newline character
System.out.print("Enter the message: ");
String content = scanner.nextLine();
Message sendMessage = new Message(MessageType.MESSAGE);
sendMessage.setUsername(username);
sendMessage.setRecipient(recipient);
sendMessage.setContent(content);
outputStream.writeObject(sendMessage);
}
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class UserInfo {
private String username;
private String ipAddress;
private int port;
public UserInfo(String username, String ipAddress, int port) {
this.username = username;
this.ipAddress = ipAddress;
this.port = port;
}
public String getUsername() {
return username;
}
public String getIpAddress() {
return ipAddress;
}
public int getPort() {
return port;
}
}
enum MessageType {
REGISTER,
QUERY,
RESPONSE,
MESSAGE
}
class Message implements java.io.Serializable {
private MessageType type;
private String username;
private String ipAddress;
private int port;
private String recipient;
private String content;
private java.util.List<UserInfo> users;
public Message(MessageType type) {
this.type = type;
users = new java.util.ArrayList<>();
}
public MessageType getType() {
return type;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public void addUser(String username, String ipAddress, int port) {
users.add(new UserInfo(username, ipAddress, port));
}
public java.util.List<UserInfo> getUsers() {
return users;
}
}
```
这个示例中的即时通信系统使用Socket通信机制实现,分为服务端和客户端两部分。客户端在启动后可以向服务器注册自己的信息,包括IP地址、端口号和用户名。客户端还可以查询其他用户的在线状态,并通过服务器实现消息的交换。服务器端维护用户的状态信息,对用户查询做出响应,并实现消息的转发。
请注意,这只是一个简单的示例,没有考虑安全性和错误处理。在实际应用中,可能需要添加更多的功能和改进。
希望这个示例对你有帮助!如果还有其他问题,请随时提问。
阅读全文