简体   繁体   中英

Multiple Clients on one server java

Ok so my one friend was teaching me networking stuff on java and we have a successful program. It is a simple chatter that we connect to with putty, but we have one problem. Only one client can connect at a time. Can someone please say how to connect more clients at a time and how to limit the number of clients connected?

public class Base 
{
  static ServerSocket serverSocket;
  public static void main(String[] args) throws IOException
  {
    final ServerSocket serverSocket = new ServerSocket (1337);
    Thread thread = new Thread(new Runnable()
                                 {
      public void run()
      {
        try
        {
          System.out.println("Waiting for connections...");
          //Make Socket on port
          Socket client = serverSocket.accept();
          System.out.println("Connection from " + client.getInetAddress());
          //initialixe no socket with connect server gets
          BufferedReader in = new BufferedReader (new InputStreamReader(client.getInputStream()));
          //init new beffer to read incom
          //while loop to read stuff
          final BufferedWriter out = new BufferedWriter(new PrintWriter(client.getOutputStream()));
          out.write("Your Connected Mate");
          out.newLine();
          out.flush();
          new Thread(new Runnable()
                       {
            public void run()
            {
              try
              {
                Scanner s = new Scanner(System.in);
                while(s.hasNext())
                {
                  out.write("CLIENT] " + s.nextLine());
                  out.newLine();
                  out.flush();
                }
              }
              catch(Exception e)
              {
                e.printStackTrace();
              }
            }
          }).start();
          while(true)
          {
            //make a string form anything thats read from the socket
            String tmp = in.readLine();
            //if the string isnt null (which it is if we disconnect) print it out
            if(tmp != null)
            {
              System.out.println("[CLIENT -> SERVER] " + tmp);
            }
          }
        }
        catch(Exception e)
        {
          e.printStackTrace();
        }
      }
    });
    thread.run();
  }
}

We haven't tried anything because we have no idea :)

I believe you need to put a while(true) loop (or while(notInterrupted) or something) around accepting connections in your client (within the existing run thread). If you're going to have the connections stay alive for a long time, I suppose you'd want to then spawn threads that handle them (use cases such as simple web servers probably don't need to spawn threads - the amount of time each client takes up is probably less than that taken by spawning a thread).

Try looking around for some example servers, and see if you can adapt them to your needs.

As for limiting the number of clients able to connect, you probably want some kind of blocking data structure that handles pools of threads, and only gives you one when one is freed up. A Thread Pool comes to mind...

Surround everything in the first try statement in a while loop that keeps repeating as long as you wish to connect another client. Then you will need to put the input code (like the in.readLine() code) in it's own Thread like you did for the Server's output ( out.write()) .

Every client needs his own input thread and output thread. Try to keep the communication between the client and the server off of the main thread so that the server can continue to accept connections.

Example code:

//Setup your ServerSocket

ServerSocket server = new ServerSocket();

while (true){
    Socket s = server.accept();
    Thread input = new Thread(new Runnable(){
            //Set up your BufferedReader or whatever input method you are using here
                      BufferedReader in = new BufferedReader (new InputStreamReader(client.getInputStream()));

            while(true)
            {
            //make a string form anything thats read from the socket
            String tmp = in.readLine();
            //if the string isnt null (which it is if we disconnect) print it out
            if(tmp != null)
            {
              System.out.println("[CLIENT -> SERVER] " + tmp);
            }
          }
        }).start();

    //Do the same for your output as you just did for your input (make a new thread, make a new writer object, etc.)
}
}

Note: this is a very rough example. You'll need to fill in some blanks and maybe some {} Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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