简体   繁体   English

Java线程:如何在代码中找到正确的位置,为允许多个客户端连接到服务器的程序创建新线程

[英]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: 这看起来很像家庭作业,所以我不会提供工作代码,但您可以尝试按照以下步骤操作:

  • Make two classes with a main-method each 使用main方法创建两个类
  • In one class create a 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". 尝试从客户端发送最简单的消息,例如包含“hello world”的行。 PrintWriter can eg be used to wrap the OutputStream of the socket in a more convenient interface. PrintWriter可以用于将套接字的OutputStream包装在更方便的界面中。
  • In the other class create a 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并打印客户端发送的内容逐行读取。
  • Ensure communication works both ways by sending/receiving responses (Server writes response to OutputStream of the socket associated with the client, client reads InputStream of it's socket) 通过发送/接收响应确保通信双向工作(服务器将响应写入与客户端关联的套接字的OutputStream ,客户端读取其套接字的InputStream
  • Implement your application's protocol over the connection 通过连接实现应用程序的协议

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.

相关问题 如何让多个客户端连接到服务器Java - How to have multiple clients connect to a server java 如何在 Java 中为断开连接的客户端杀死服务器中的线程 - How to Kill Threads in Server for Disconnected Clients in Java 创建一个允许通过线程和Java进行多个连接的套接字服务器 - Creating a socket server which allows multiple connections via threads and Java Java中如何方便服务器线程和多个客户端线程之间的通信 - How to facilitate communication between the server thread and the multiple client threads in Java 如何创建一个侦听端口并接受多个客户端的Java服务器 - How to create a Java server which listens to a port and accepts multiple clients 如何在Java套接字编程中用单个服务器创建多个客户端? - how to create multiple clients with single server in java socket programming? Java:如何在单个线程中与多个客户端进行通信 - Java: How to communicate with multiple clients in a single thread Java服务器-多个客户端处理-使用线程是否最优? - Java server - multiple clients handling - is using threads optimal? Java客户端服务器/一个线程多个客户端 - Java client-server / one thread multiple clients 如何防止套接字在具有多个线程的程序中变为空(Java套接字线程编程) - How to prevent socket from becoming null in a program with multiple threads (java socket thread programming)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM