给我一个代码基于TCP协议的聊天程序的设计与实现可注册用户java
时间: 2023-11-16 09:05:36 浏览: 84
好的,以下是一个基于TCP协议的聊天程序的设计与实现,同时支持用户注册和登陆的 Java 代码:
1. 服务器端代码:
```java
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
private static final int PORT = 8888;
private static Map<String, Socket> clients = new HashMap<String, Socket>();
private static Map<String, String> users = new HashMap<String, String>();
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Server started...");
while (true) {
Socket client = serverSocket.accept();
System.out.println("Client connected: " + client.getInetAddress().getHostAddress());
new ChatHandler(client).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static synchronized boolean register(String username, String password) {
if (users.containsKey(username)) {
return false;
} else {
users.put(username, password);
return true;
}
}
private static class ChatHandler extends Thread {
private Socket client;
private String username;
public ChatHandler(Socket client) {
this.client = client;
}
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
out.println("Welcome to the chat server!");
out.println("Please login or register.");
while (true) {
String line = in.readLine();
if (line.startsWith("REGISTER")) {
String[] tokens = line.split("\\s+");
boolean success = register(tokens[1], tokens[2]);
if (success) {
out.println("REGISTERED");
} else {
out.println("REGISTER FAILED");
}
} else if (line.startsWith("LOGIN")) {
String[] tokens = line.split("\\s+");
if (users.containsKey(tokens[1]) && users.get(tokens[1]).equals(tokens[2])) {
username = tokens[1];
clients.put(username, client);
out.println("LOGIN SUCCESS");
break;
} else {
out.println("LOGIN FAILED");
}
} else {
out.println("Invalid command.");
}
}
out.println("Welcome, " + username + "!");
BufferedReader consoleIn = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String input = consoleIn.readLine();
if (input.equalsIgnoreCase("quit")) {
out.println("QUIT");
break;
} else {
String[] tokens = input.split("\\s+", 2);
if (tokens.length == 2) {
Socket targetClient = clients.get(tokens[0]);
if (targetClient != null) {
PrintWriter targetOut = new PrintWriter(targetClient.getOutputStream(), true);
targetOut.println(username + ": " + tokens[1]);
} else {
out.println("User not found.");
}
} else {
out.println("Invalid command.");
}
}
}
clients.remove(username);
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
2. 客户端代码:
```java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ChatClient {
private static final int PORT = 8888;
private static final String HOST = "localhost";
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket(HOST, PORT);
System.out.println("Connected to server.");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner consoleIn = new Scanner(System.in);
while (true) {
String line = in.readLine();
if (line.startsWith("LOGIN")) {
System.out.println(line);
String[] tokens = consoleIn.nextLine().split("\\s+");
out.println("LOGIN " + tokens[0] + " " + tokens[1]);
} else if (line.startsWith("REGISTER")) {
System.out.println(line);
String[] tokens = consoleIn.nextLine().split("\\s+");
out.println("REGISTER " + tokens[0] + " " + tokens[1]);
} else if (line.startsWith("LOGIN SUCCESS")) {
System.out.println(line);
break;
} else if (line.startsWith("LOGIN FAILED") || line.startsWith("REGISTER FAILED")) {
System.out.println(line);
} else {
System.out.println(line);
break;
}
}
new Thread(new Runnable() {
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String line = in.readLine();
if (line.startsWith("QUIT")) {
break;
} else {
System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
while (true) {
String input = consoleIn.nextLine();
out.println(input);
if (input.equalsIgnoreCase("quit")) {
break;
}
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个聊天程序使用了多线程,每个客户端连接上服务器后,都会开启一个新的线程进行处理。服务器端维护了两个 Map,一个用于保存所有注册的用户(用户名和密码),另一个用于保存在线用户(用户名和对应的 Socket)。客户端可以使用 REGISTER 命令进行注册,使用 LOGIN 命令进行登陆。登陆成功后,客户端可以通过输入用户名和消息来向其他在线用户发送消息。如果输入“quit”,客户端会退出聊天室。
阅读全文