gpt4 book ai didi

带有命令的 Java 聊天服务器

转载 作者:可可西里 更新时间:2023-11-01 02:41:36 25 4
gpt4 key购买 nike

所以我正在用 Java 制作一个聊天服务器,以便在我的 Minecraft 服务器中不再依赖 Hamachi 进行托管和通信。它工作完美,除了一件事:我无法弄清楚我的生活如何向服务器添加命令。我的主循环如下:

/*Executed in constructor*/
public void listen(int port) throws IOException {
//Initialize the ServerSocket
ss = new ServerSocket(port);
System.out.println("Listening on " + InetAddress.getLocalHost() + ":" + ss.getLocalPort());

running = true;

//Keep accepting connections
while (running) {
//Get the incoming connection
Socket s = ss.accept();
System.out.println("Connection from: " + getFullIP(s));

//Create a DataOutputStream for writing data to the other side
DataOutputStream dataOut = new DataOutputStream(s.getOutputStream());

//Save this stream so I don't have to make it again
outputStreams.put(s, dataOut);

//Create a new thread for this connection
new ServerThread(this, s);

if (!running) {
stop();
}
Scanner cmdScanner = new Scanner(System.in);
String command = cmdScanner.next();
processCommand(command);
}
}

此代码的结果是,在客户端连接到服务器之前我无法键入命令(因为 ss.accept())。在我执行命令之前,客户端无法连接 (cmdScanner.next())。我该如何解决这个问题?

最佳答案

我认为您的命令处理器应该在另一个线程中。恕我直言,服务器应该始终有一个线程,唯一的工作是接收新连接并分发它。处理您的输入应该是另一个线程的一部分。

public class TestThread
{
public static void main(String[] args)
{
new ConnectionDispatcher(8080).start();
new CommandProcessor().start();
}
}
class ConnectionDispatcher extends Thread{
private int port;
private OutputStream outputStreams;

ConnectionDispatcher(int port)
{
this.port = port;
}

@Override
public void run()
{
try
{
listen(port);
}
catch (IOException e)
{
e.printStackTrace();
}
}

public void listen(int port) throws IOException
{
//Initialize the ServerSocket
ss = new ServerSocket(port);
System.out.println("Listening on " + InetAddress.getLocalHost() + ":" + ss.getLocalPort());

boolean running = true;

//Keep accepting connections
while (running) {
//Get the incoming connection
Socket s = ss.accept();
System.out.println("Connection from: " + getFullIP(s));

//Create a DataOutputStream for writing data to the other side
DataOutputStream dataOut = new DataOutputStream(s.getOutputStream());

//Save this stream so I don't have to make it again
outputStreams.put(s, dataOut);

//Create a new thread for this connection
new ServerThread(this, s);

}
}
}

class CommandProcessor extends Thread{
@Override
public void run()
{
Scanner cmdScanner = new Scanner(System.in);
String command = cmdScanner.next();
processCommand(command);
}
}

关于带有命令的 Java 聊天服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10874782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com