[英]Java Threads: How to find the right place in code to create a new thread for a program that allows multiple clients to connect to the server
I'm creating two program files (one client one server). 我正在创建两个程序文件(一个客户端一个服务器)。 The client code has to be able to create multiple clients to connect to the server (there is only one server, there can be a multiple and/or infinite number of clients).
客户端代码必须能够创建多个客户端才能连接到服务器(只有一个服务器,可以有多个和/或无限数量的客户端)。 One new thread has to be created for each client that connects to the server.
必须为连接到服务器的每个客户端创建一个新线程。 The way to create a client will be opening a new command prompt / mac terminal window and run the client file.
创建客户端的方法是打开一个新的命令提示符/ mac终端窗口并运行客户端文件。 Once a client is connected, it can send messages to the server.
连接客户端后,它可以向服务器发送消息。 It will also receive from the server all messages sent from the other connected clients.
它还将从服务器接收从其他连接的客户端发送的所有消息。
We will focus on the client code for now. 我们现在将重点关注客户端代码。 (no server code yet)
(还没有服务器代码)
In the following code there are two places where I created new threads, I am not sure which place it should be located because there are no errors when I run the program in eclipse. 在下面的代码中有两个地方我创建了新的线程,我不确定它应该位于哪个位置因为在eclipse中运行程序时没有错误。
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatClient
{
private static Socket Socket;
static int numberOfClients = 0;
public static void main(String args[])
{
//If I wanted to create multiple clients, would this code go here? OR should the new thread creation be outside the while(true) loop?
while (true)
{
try
{
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
numberOfClients += 1;
Thread ChatClient1 = new Thread ()
{
public void run()
{
ServerSocket serverSocket = null;
Socket socket = null;
try
{
int numberofmessages = 0;
String[] messagessentbyotherclients = null;
System.out.println("Try block begins..");
System.out.println("Chat client is running");
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + port_number1 );
serverSocket = new ServerSocket(port);
for(int i = 0; i < numberOfClients; i++)
{
System.out.println(messagessentbyotherclients);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
};
ChatClient1.start();
}
catch (IOException e)
{
System.out.println("I/O error: " + e);
}
}
}
} My question is: Should the thread be created right underneath the main function or inside the while(true) loop? 我的问题是:是应该在主函数下面还是在while(true)循环内创建线程? (the while true loop will eventually be exited by control D in standard input)
(while循环最终将由标准输入中的控件D退出)
Your code is so far from a working solution, that I don't think commenting on it is helpful to you at this point. 您的代码远不是一个有效的解决方案,我不认为评论它对您有帮助。 As people in comments have already explained you should have 2 executables for client and server.
正如评论中的人已经解释过,您应该为客户端和服务器提供2个可执行文件。 What you do right now is to spawn server threads in the inner loops without any chance of creating more than one client that connects to the same server.
您现在所做的是在内部循环中生成服务器线程,而不会创建连接到同一服务器的多个客户端。
The usual way to write a multi-threaded client/server app using one thread per client is to write a server-executable, which opens a ServerSocket
, which does accept
and spawns a new Thread
to handle the client-socket in a loop. 使用每个客户端一个线程编写多线程客户端/服务器应用程序的常用方法是编写一个服务器可执行文件,它打开一个
ServerSocket
,它accept
并生成一个新的Thread
来处理循环中的客户端套接字。
Then you write a client-executable, which uses a Socket
to connect
to the server (on the port used to spawn the server), and talks to the server. 然后编写一个客户端可执行文件,它使用
Socket
connect
到服务器(在用于生成服务器的端口上),并与服务器通信。
Communication can be done using the input/output streams you get from the sockets at both ends of the connection. 可以使用从连接两端的套接字获得的输入/输出流来完成通信。
This looks a lot like homework, so I won't provide working code, but you can try to follow these steps: 这看起来很像家庭作业,所以我不会提供工作代码,但您可以尝试按照以下步骤操作:
Socket
, which calls connect
to the server. Socket
,它调用connect
到服务器。 Try to send the simplest possible message from the client, such as a line containing "hello world". PrintWriter
can eg be used to wrap the OutputStream
of the socket in a more convenient interface. PrintWriter
可以用于将套接字的OutputStream
包装在更方便的界面中。 ServerSocket
and call accept
in a loop, handing the returned Socket
s to new Thread
s, which loop over the input from the client until a terminating signal is received from the client or the connection is closed (IOException). ServerSocket
并在循环中调用accept
,将返回的Socket
交给新的Thread
,它循环来自客户端的输入,直到从客户端收到终止信号或连接关闭(IOException)。 You can start with reading line by line by wrapping the InputStream
in a BufferedReader
and just printing what the client sends. InputStream
包装在BufferedReader
并打印客户端发送的内容逐行读取。 OutputStream
of the socket associated with the client, client reads InputStream
of it's socket) OutputStream
,客户端读取其套接字的InputStream
) When you are done, you first start the server, then run as many clients against it as you want. 完成后,首先启动服务器,然后根据需要运行多个客户端。 The server needs to be started first, because the
connect
call will internally open a connection, which can only be completed, if a server is listening on the port the client connects to. 需要首先启动服务器,因为如果服务器正在侦听客户端连接的端口,则
connect
调用将在内部打开一个连接,该连接只能完成。 If the threading is complicated at all for you, try writing a server that just accepts a connection, then reads a line from it, and closes it before adding the threaded logic. 如果线程很复杂,请尝试编写一个只接受连接的服务器,然后从中读取一行,并在添加线程逻辑之前将其关闭。 From your code it seems to me like you don't seem to fully understand how a client/server-connection works.
在您的代码中,我觉得您似乎并不完全了解客户端/服务器连接的工作原理。 Right now you can't even have one client, because - all other issues aside - you call neither
accept
nor connect
. 现在你甚至不能拥有一个客户,因为 - 除了所有其他问题 - 你既不
accept
也不connect
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.