简体   繁体   English

多线程java程序中将“ serverSocket.accept();”行放置在何处

[英]Where to put the line “serverSocket.accept();” in a multithreaded java program

I am trying to create a program where the server and client can send and receive messages to/from each other at the same time (the same way two people with phones can text each other) 我正在尝试创建一个程序,使服务器和客户端可以同时相互收发消息(两个有电话的人可以互相发短信)

There are three files (the main function file, the server file, the client file) I want to only focus on server and main file for now. 我现在只想关注服务器和主文件这三个文件(主要功能文件,服务器文件,客户端文件)。

The problem with the server file is that there are two separate threads where each thread has its own separate "run" function so I am wondering where I should put the "socket.accept()" line in order to make both of them work (perhaps before, globally somehow?) 服务器文件的问题在于,有两个单独的线程,其中每个线程都有自己单独的“运行”功能,因此我想知道应该在哪里放置“ socket.accept()”行,以使它们都可以工作(也许以前,在全球范围内?)

The command line arguments to run the server are 运行服务器的命令行参数是

java DirectMessengerCombined -l 3000

if "-l" is not present, then it will run as a client 如果“ -l”不存在,它将作为客户端运行

The flow of the Server file I think would go something like this (psuedo-code comments) (correct me if I'm wrong) 我认为服务器文件的流将是这样的(伪代码注释)(如果我错了,请纠正我)

//Server listens for connections 
//then accepts the connection from client
//Recieving msesages:
        //function recieves messages, create and run a functon that recieves messages
        //read from the socket until the other side closes
        //display the recieved message


//Sending: Standard input begins
        //create and run a functon that sends messages
        //write using standard input as long as the user doesn't close it, in a loop


//user close standard input to end the program

According to this flow, would it be possible to accept a connection outside the first run method from the thread? 根据此流程,是否可以从线程的第一个run方法之外接受连接? Perhaps in the constructor? 也许在构造函数中?

Server Code: 服务器代码:

import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class DirectMessengerServer
{

    private String[] serverArgs; 
    private static Socket socket;
    public boolean keepRunning = true;

    public DirectMessengerServer(String[] args) throws IOException 
    {

        // should serverSocket.accept() go here???



        // set the instance variable
        this.serverArgs = args;
        int port_number1 = Integer.valueOf(serverArgs[1]);
        ServerSocket serverSocket = new ServerSocket(port_number1);
        socket = serverSocket.accept(); 
    }

      public String[] ServerRun(String[] args) 
      {
        serverArgs = args;
        serverArgs = Arrays.copyOf(args, args.length);
        return serverArgs;
      }


        // should serverSocket.accept() go here???

    Thread ServerRecieve = new Thread();


//If i put serverSocket.accept() in both the run methods, won't that cause an "Address already in use error"? 

//run method of ServerRecieve
public void run(String args[])
{   
    System.out.println("Server recieve thread is now running");
    try
    {


        while(keepRunning)
        {
            //Reading the message from the client


            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String MessageFromClient = br.readLine();
            System.out.println("Message received from client: "+ MessageFromClient);


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

Thread ServerSend = new Thread ();

//Run method of ServerSend
public void run()
{   
    while(keepRunning)
    {
        System.out.println("Server sending thread is now running");
        try
        {         

            //Send the message to the server
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);

            //creating message to send from standard input
            String newmessage = "";
            try 
            {
                // input the message from standard input
                BufferedReader input= new BufferedReader( 
                        new InputStreamReader(System.in));
                String line = "";

                line= input.readLine(); 
                    newmessage += line + " ";

            }
            catch ( Exception e )
            {
                System.out.println( e.getMessage() );
            }
            String sendMessage = newmessage;
            bw.write(sendMessage + "\n");
            bw.flush();
            System.out.println("Message sent to client: "+sendMessage);
        }


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

        }
    }
}


}

Code of main function file: 主要功能文件代码:

import java.io.IOException;

public class DirectMessengerCombined
{
    public static void main(String[] args) throws IOException
    {
        DirectMessengerClient Client1 = new DirectMessengerClient();
    //  Thread t1 = new Thread(Client1);
        DirectMessengerServer Server1 = new DirectMessengerServer(args);
        //DirectMessengerServer Server1 = new DirectMessengerServer(args[1], null, 0);
          for (int i = 0; i < args.length; i++)
          {
                if(!args[0].equals("-l"))
                {
                    Client1.ClientRun(args);
                }
                switch (args[0].charAt(0))
                {
                    case '-':
                    if(args[0].equals("-l"))
                    {   
                        Server1.ServerRun(args);
                    }

                }
           i=args.length + 20;
          } 
    }

}

My question is: where is the right place to accept the connections in the code so that both run methods will be able to work as if they both were connected? 我的问题是:在代码中哪个位置可以接受连接,以便两个运行方法都能正常工作,就像它们都已连接一样?

通常,您会将其放入其自己的线程的循环中,并在每个接受的连接中启动一个新线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM