通过使用java.net实现客户端向服务端发送信息内容以及发送目标地址ID,服务端通过寻找对应ID转发给目标客户端。
代码仅供参考,其中有很多地方仍需要优化,比如:ID无法注册、没有添加密码、代码优化不够等问题
java版本:17
服务端代码:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.*;
import java.util.*;
public class Sever {
public static Sever Instance;
private static int port = 9999;
private String[] id = {"1", "2", "3", "4", "5"};//ID为固定ID,可根据需求添加或更改
Map<String, PrintWriter> land_id = new HashMap<>();
//判断账号输入是否存在
public boolean JudgeID(String id_)
{
for(int i = 0;i < id.length;i++)
{
if(Objects.equals(id_, id[i]))
{
return true;
}
}
return false;
}
public void AddLandID(String id_, PrintWriter writer)
{
land_id.put(id_,writer);
}
public static void main(String[] args) throws IOException {
Instance = new Sever();//通过使用单例来实现其他模块代码调用
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("服务器已启动,等待客户端连接...");
//死循环使服务端一直运行
while (true) {
Socket clientSocket = null; // 接受客户端连接
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
throw new RuntimeException(e);
}
new ClientWorking(clientSocket).start(); //为每个客户端创建一个新的线程处理
}
}
}
客户端进程代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Objects;
public class ClientWorking extends Thread {
private Socket clientSocket;
private String clientId;
private BufferedReader reader;
private PrintWriter writer;
private String aimId;
public ClientWorking(Socket socket) {
this.clientSocket = socket;
}
//重写进程运行代码,主要包括对客户端发送的信息进行处理
@Override
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
writer = new PrintWriter(clientSocket.getOutputStream(), true);
// 登录过程,接收客户端ID
while(true)
{
writer.println("请输入你的ID(输入/q断开连接):");//ID为服务端指定ID
clientId = reader.readLine();
if (Sever.Instance.JudgeID(clientId)) {
Sever.Instance.AddLandID(clientId, writer);
System.out.println(clientId + " 已连接.");
while(true)
{
writer.println("请输入你要发送信息到的目标ID:");
aimId = reader.readLine();
if (Objects.equals(aimId, "/q"))
{
System.out.println(clientId + " 已断开.");
return;
}
else if (Sever.Instance.land_id.containsKey(aimId)) {
String message;
while (true)
{
writer.println("(输入q退出)->");
if((message = reader.readLine()) != null)
{
System.out.println("收到来自 " + clientId + " 的消息: " + message);
if(message.equals("q"))
{
break;
}
else
{
PrintWriter targetWriter = (Sever.Instance.land_id.get(aimId));
targetWriter.println(clientId + ": " + message);
}
}
}
}
else
{
writer.println("未找到用户,请再次输入(输入/q退出)");
}
}
}
else if (Objects.equals(clientId, "/q"))
{
System.out.println(clientId + " 已断开.");
return;
}
else
{
writer.println("输入id错误,请重新输入");
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
客户端代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Objects;
import java.util.Scanner;
public class Client {
private static final String SERVER_ADDRESS = "localhost";
private static final int SERVER_PORT = 9999;
public static void main(String[] args) {
try (Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader serverReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter serverWriter = new PrintWriter(socket.getOutputStream(), true)) {
System.out.println("连接到服务器成功.");
// 登录
System.out.println(serverReader.readLine()); // 服务器发送登录提示
Scanner in = new Scanner(System.in);
String clientId = in.next();
serverWriter.println(clientId);
if (clientId.equalsIgnoreCase("/q")) {
serverWriter.println(clientId);
return;
}
// 新建线程持续接收服务器反馈的消息
new Thread(() -> {
try {
String serverMessage;
while ((serverMessage = serverReader.readLine()) != null) {
System.out.println(serverMessage); // 打印来自服务器的消息1
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
// 死循环持续检测发送消息
while (true) {
//System.out.print("请输入消息 (格式: 目标ID: 消息内容) 或 输入 'exit' 退出: ");
String message = consoleReader.readLine();
serverWriter.println(message);
if (message.equalsIgnoreCase("/q")) {
serverWriter.println(message);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
标签:java,String,new,clientId,import,println,JAVA,NET,服务端
From: https://blog.csdn.net/qq_73300425/article/details/144274728