【问题标题】:How can I use multi-threading to allow multiple clients on to a server? [duplicate]如何使用多线程允许多个客户端连接到服务器? [复制]
【发布时间】:2016-02-08 15:18:30
【问题描述】:

我有两个 java 类,一个用于服务器,一个用于客户端。使用常规套接字在它们之间建立连接。如何允许客户端类的多个实例使用多线程同时连接到服务器? 我尝试在 SO 上进行搜索,但我真的找不到任何简明/清晰的答案。

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

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());

}

【问题讨论】:

  • 一种“传统”方法是在服务器上为每个客户端生成一个新线程;使用ServerSocket。根据您的应用程序,您可能可以使用Selector 来减少所需的线程数。网上有很多例子。但是,您的问题对于本网站的格式来说太宽泛了。请就您编写的某些代码提出具体问题。

标签: java multithreading sockets server client


【解决方案1】:

这是一个简单的例子。一个新的线程回复每个新的传入客户端。

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 !");
  }
}

【讨论】:

  • 我的服务器类已经在扩展 JFrame,您介意编辑它以实现 Runnable 接口吗?
  • 完成了。如您所见,变化不大
  • 构造函数中的超级调用是什么?
  • 我现在必须删除它,因为服务器不再扩展线程......
  • 我了解您的代码,但我只是不知道如何将其应用于我的代码。我已经编辑了我的问题以包含最重要的方法。任何帮助表示赞赏!
猜你喜欢
  • 1970-01-01
  • 2023-03-09
  • 2015-06-01
  • 2015-03-24
  • 2021-08-17
  • 2018-04-28
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多