我如何使用多线程来允许一个服务器上有多个客户端? [英] How can I use multi-threading to allow multiple clients on to a server?

查看:250
本文介绍了我如何使用多线程来允许一个服务器上有多个客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个Java类,一个用于服务器,一个用于客户端.两者之间使用常规插座建立连接.如何允许客户端类的许多实例使用多线程同时连接到服务器? 我尝试在SO上进行搜索,但找不到真正简洁明了的答案.

I have two java classes, one for a server and one for a client. The connection is established between both of them using a regular socket. How can I allow many instances of the client class to connect to the server simultaneously using multi-threading? I tried searching on SO but I couldn't really find any concise/clear answers.

这是我重要的方法(它们都在Server类中):

Here are my important methods (both of them are in the Server class):

public void startRunning() {

    try {
        server = new ServerSocket(portNum, 10); // port num and backlog

        while (true) {
            try {

                waitForConnection();
                setupStreams();  //sets up streams
                whileChatting(); //exchanges messages
            } catch (EOFException e1) {
                showMessage("\n Server ended the connection");

            } finally {
                closeEverything();  //closes all streams
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private void waitForConnection() throws IOException {

    showMessage(" Waiting for connections...\n");
    connection = server.accept();
    showMessage(" Connected to "
            + connection.getInetAddress().getHostName());

}

推荐答案

这是一个简单的示例.一个新的线程回复到每个新的传入客户端.

Here is a simple example. A new Thread replies to every new incoming Client.

import java.io.*;
import java.net.*;

class Server implements Runnable {
  public static final int port = 5678;


  public void run() {
    try{
       ServerSocket server = new ServerSocket(port);

       while (true) 
       {
           final Socket client = server.accept();
           new Thread() {
                public void run() {
                      try{
                          ObjectInputStream in = 
                          new ObjectInputStream( client.getInputStream() );
                         String msg = (String) in.readObject();
                         System.out.println(msg);
                        }
                      catch(Exception e){System.err.println(e);}

          }}.start();
       }
      }
    catch(IOException e){System.err.println(e);}
    }

}

class Client {

  public void writeMessage(String msg) throws IOException {
     new ObjectOutputStream((new Socket("localhost",Server.port).getOutputStream())).writeObject(msg);
  }
}

public class ClientServer{
  public static void main(String[] args) throws IOException{
    Server server = new Server("My Multithreaded Server");
    new Thread(server).start();
    Client client1 = new Client();
    Client client2 = new Client();
    client1.writeMessage("Hello !");
    client2.writeMessage("Give me five !");
  }
}

这篇关于我如何使用多线程来允许一个服务器上有多个客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆