Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java服务器套接字编程:如何向发送消息的客户端以外的所有其他客户端发送消息_Java_Multithreading_Sockets - Fatal编程技术网

Java服务器套接字编程:如何向发送消息的客户端以外的所有其他客户端发送消息

Java服务器套接字编程:如何向发送消息的客户端以外的所有其他客户端发送消息,java,multithreading,sockets,Java,Multithreading,Sockets,我正在尝试创建一个聊天程序,将多个客户端连接到一台服务器,服务器需要能够将收到的消息(utf-8字符串)分发到发送消息的客户端之外的所有其他客户端。我有一个客户列表(每个客户在arraylist中都有一个位置)。所有客户端都连接到同一端口上的服务器 要运行的服务器/客户端的命令行参数 java ChatServer 1234 java ChatClient 1234 这里是我当前拥有的代码,用于将接收到的消息发送回发送消息的客户端之外的所有其他客户端(当前不起作用) (下面的代码在一个名为Ch

我正在尝试创建一个聊天程序,将多个客户端连接到一台服务器,服务器需要能够将收到的消息(utf-8字符串)分发到发送消息的客户端之外的所有其他客户端。我有一个客户列表(每个客户在arraylist中都有一个位置)。所有客户端都连接到同一端口上的服务器

要运行的服务器/客户端的命令行参数

java ChatServer 1234
java ChatClient 1234
这里是我当前拥有的代码,用于将接收到的消息发送回发送消息的客户端之外的所有其他客户端(当前不起作用)

(下面的代码在一个名为ChatServer的类中)(这是一个原型,不是正确的/最佳的解决方案,我只是把它作为我的第一个粗略想法,当我学会如何正确分发收到的消息时,可能会改变它)


我的问题是:如何将接收到的消息(作为服务器)发送给列表中的所有客户机(发送消息的原始客户机除外?

重构,不要像现在这样在大型God类中做所有事情。我自己不会使用
列表
,而是使用
列表
,帮助器类包含与之通信所需的所有内容,包括perhpas唯一的字符串ID。这样,您可以获得发送消息的连接的ID,并发送给所有具有不同ID的帮助器。另外,你会想要学习和使用。变量名都应该以小写字母开头,而类名应该以大写字母开头。学习这一点并遵循这一点可以让我们更好地理解您的代码,也可以让您更好地理解其他人的代码。@hovercraftfullofels我明白了。因此,代替ArrayList ListofClient=new ArrayList();我应该使用List-listofClient=new-List();正确的?
//create variables to keep track of position
int position = 0;

int max = ListOfClients.size();

//create for loop to search through list of clients
for(int j = 0; j < max; j++)
{
   //This if-statment is what I want to change to make it work. 
   //How would I code "if(this client is not the original one that sent me a message
   if(j != 0 && j < max)
   {
      //send message to all other clients besides the one that sent it
      max++;
      OutputStream os = socket.getOutputStream();
      OutputStreamWriter osw = new OutputStreamWriter(os);
      BufferedWriter bw = new BufferedWriter(osw);
      bw.write(relayMessage + "\n");
      System.out.println("Message relayed to client: "+ relayMessage);
      bw.flush();   
      j=j-1;

   }
}        
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatServer
{

    private static Socket socket;
    static //create a list of clients
    ArrayList<Socket> ListOfClients = new ArrayList<Socket>();
    public static void main(String[] args)
    {
        boolean KeepRunning = true;
        Thread Listening = new Thread () 
        {
            public void run ()
            {   
                System.out.println("Server thread is now running");
                try
                {
                    System.out.println("Try block begins..");
                    int port_number1= Integer.valueOf(args[0]);
                    System.out.println("Port number is: " + port_number1);
                    ServerSocket serverSocket = new ServerSocket(port_number1);
                    //SocketAddress addr = new InetSocketAddress(address, port_number1);
                    System.out.println( "Listening for connections on port: " + ( port_number1 ) );
                    boolean KeepRunning = true;
                    while(KeepRunning)
                    {

                        //Connect to the client
                        socket = serverSocket.accept();
                        //ListOfClients.add(socket);
                        Thread RecievingAndSending = new Thread()
                        {
                            public void run()
                            {
                                try
                                {
                                    if(socket!=null)
                                    {
                                        ListOfClients.add(socket);
                                        //ChatServer client = new ChatServer();
                                        //client.setUniqueId(uniqueID);
                                        //int listsize = ListOfClients.size();
                                        //UUID uniqueID = UUID.randomUUID(); 
                                        //System.out.println("This client's id is"+ uniqueID);

                                        //reading message form client
                                        BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));  
                                        String relayMessage = BufReader1.readLine();


                                        //relaying message to every other client besides the one it was from
                                        if(relayMessage == "" || relayMessage == null)
                                        {
                                            System.exit(0);

                                        }   
                                        else //this is where the question is
                                        {
                                            //int position = 0;
                                            //int max = ListOfClients.size();
                                            //for(int j = 0; j < max; j++)
                                            //{
                                                //if(j != 0 && j < max)
                                            //  {
                                                 // max++;
                                                  OutputStream os = socket.getOutputStream();
                                                  OutputStreamWriter osw = new OutputStreamWriter(os);
                                                  BufferedWriter bw = new BufferedWriter(osw);
                                                  bw.write(relayMessage + "\n");
                                                  System.out.println("Message relayed to client: "+ relayMessage);
                                                  bw.flush();   
                                                //  j=j-1;

                                                //}
                                            //}
                                        }


                                    OutputStream os = socket.getOutputStream();
                                    OutputStreamWriter osw = new OutputStreamWriter(os);
                                    BufferedWriter bw = new BufferedWriter(osw);

                                            bw.flush();
                                    }

                                        } catch (UnsupportedEncodingException e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace();
                                        } catch (IOException e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace();
                                        }
                                        finally
                                        {

                                        }
                                    }
                                };
                                RecievingAndSending.start();

                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                finally
                {

                }

            }
        };
        Listening.start();

    }
}
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatClient
{
    final int numberOfClients = 0;
    private static Socket socket;
    public static void main(String args[]) 
    {

        UUID uuid = UUID.randomUUID();
        ChatClient chatclient = new ChatClient();
        Object uniqueID = null;
        chatclient.setUniqueId(uniqueID);

                  String host = "localhost";
                  int numberOfClients = 0;
                  Thread ChatClient1 = new Thread ()
                  {
                      public void run()
                      {
                          boolean KeepRunning = true;
                          while(KeepRunning == true && args.length > 0)
                          {

                              try
                              {

                                  //Client begins, gets port number, listens, connects, prints out messages from other clients
                                  int port = 0;
                                  int port_1number1 = 0;
                                  int numberofmessages = 0;


                                  System.out.println("Try block begins..");
                                  System.out.println("Chat client is running");
                                  System.out.println("Port number is: " + args[0]);
                                  port = Integer.valueOf(args[0]);
                                  System.out.println("Listening for connections..");
                                  System.out.println( "Listening on port: " + args[0] );
                                  // System.out.println(messagessentbyotherclients);

                                  socket = new Socket("localhost", port);
                                  InetAddress inetlocalhost = InetAddress.getByName("localhost");
                                  SocketAddress localhost = new InetSocketAddress(inetlocalhost, port);
                                  //socket.connect(localhost, port);
                                  System.out.println("Client has connected");



                                  //client creates new message from standard input
                                  OutputStream os = socket.getOutputStream();
                                  OutputStreamWriter osw = new OutputStreamWriter(os);
                                  BufferedWriter bw = new BufferedWriter(osw);



                                  //creating message to send from standard input
                                  String newmessage = "";
                                  try   
                                  {
                                      int k = 3;
                                      if(k==3)
                                      {
                                          // input the message from standard input encoded in UTF-8 string format
                                          BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
                                          String line = "";
                                          System.out.println( "Standard input (press enter then control D when finished): " );
                                          while( (line= input.readLine()) != null && k==3 )     
                                          {
                                              newmessage += line + " ";
                                              k=4;
                                          }
                                          k=6;
                                      }
                                  }
                                  catch ( Exception e )
                                  {
                                      System.out.println( e.getMessage() );
                                  }
                                  //Sending the message to server
                                  String sendMessage = newmessage;
                                  try 
                                  {
                                  //  Socket clientSocket = new Socket("localhost", port);
                                    InetAddress addr = InetAddress.getByName("localhost");
                                   // SocketAddress sockaddr = new InetSocketAddress(addr, port);
                                    //OutputStream os1 = socket.getOutputStream();
                                    //OutputStreamWriter osw2 = new OutputStreamWriter(os1);
                                    //BufferedWriter bw = new BufferedWriter(osw2);
                                    bw.write(sendMessage + "\n");
                                    bw.flush();
                                    //bw.close();
                                    //out.close();
                                    //os.close();

                                  } 
                                  catch (IOException e)
                                  {
                                    e.printStackTrace();
                                  }
                                  System.out.println("Message sent to server: "+sendMessage);

                                  //recieve messages from sever 
                                  //Get the return message from the server
                                  InputStream is = socket.getInputStream();
                                  InputStreamReader isr = new InputStreamReader(is);
                                  BufferedReader br = new BufferedReader(isr);
                                  String message = br.readLine();
                                  System.out.println("Message relayed from the server : " +message);

                              } catch (UnknownHostException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            } catch (IOException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            }
                              finally
                              {

                              }

                            //  KeepRunning = false;
                          }

                      }

                  };
                  ChatClient1.start();  
    }
    private void setUniqueId(Object uniqueID)
    {
        uniqueID = Math.random();

    }
}