繁体   English   中英

在服务于Socket连接的两个线程之间共享公共数据

[英]Share common data between two threads serving a Socket connection

我在SO上看到了很多类似的问题,但几乎没有任何人在图片中有Socket 所以请花些时间阅读这个问题。

我有服务器应用程序(使用ServerSocket )侦听请求,当客户端尝试连接时,创建新线程以服务客户端(并且服务器返回到新请求的侦听模式)。 现在,我需要根据其他客户端发送到服务器的内容来响应一个客户端。

例:

  • ServerSocket侦听传入连接。
  • 客户端A连接,创建新线程以服务A.
  • 客户端B连接,创建新线程以服务B.
  • A向服务器发送消息“Hello from A”。
  • 将此消息作为对客户B的响应发送。

我对这整个“线程间通信”的事情不熟悉。 显然,上面提到的情况听起来很简单,但我正在描述这一点以获得提示,因为我将在客户端之间交换大量数据,将服务器保持为中间状态。

另外,如果我想将共享对象限制为10个特定客户端,该怎么办? 这样,当第11个客户端连接到服务器时,我创建了新的共享对象,该对象将用于在第11,第12,第13 ......到第20个客户端之间交换数据。 等等每一组10个客户端。

我尝试了什么:(我猜是愚蠢的)

  • 我有一个public类,该对象应该作为public static共享,以便我可以将其用作全局而不实例化它,如MyGlobalClass.SharedMsg
  • 这不起作用,我无法将一个线程中收到的数据发送给另一个线程。

我知道存在明显的锁定问题,因为如果一个线程正在写入一个对象,则其他线程在第一个线程完成写入之前无法访问它。

那么这个问题的理想方法是什么呢?

更新

由于我创建线程来提供传入连接请求的方式,我无法理解如何在线程之间共享相同的对象,因为如上所述使用Global对象不起作用。

以下是我如何监听传入连接并动态创建服务线程。

// Method of server class
public void startServer()
{
    if (!isRunning)
    {
        try
        {
            isRunning = true;
            while (isRunning)
            {
                try
                {
                    new ClientHandler(mysocketserver.accept()).start();
                }
                catch (SocketTimeoutException ex)
                {
                    //nothing to perform here, go back again to listening.
                }
                catch (SocketException ex)
                {
                    //Not to handle, since I'll stop the server using SocketServer's close() method, and its going to throw SocketException anyway.
                }
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
    else
        System.out.println("Server Already Started!");
}

ClientHandler类。

public class ClientHandler extends Thread
{
    private Socket client = null;
    private ObjectInputStream in = null;
    private ObjectOutputStream out = null;

    public ClientHandler(Socket client)
    {
        super("ClientHandler");
        this.client = client;
    }

    //This run() is common for every Client that connects, and that's where the problem is.
    public void run()
    {
        try
        {
            in = new ObjectInputStream(client.getInputStream());
            out = new ObjectOutputStream(client.getOutputStream());

            //Message received from this thread.
            String msg = in.readObject().toString();
            System.out.println("Client @ "+ client.getInetAddress().getHostAddress() +" Says : "+msg);


            //Response to this client.
            out.writeObject("Message Received");

            out.close();
            in.close();
            client.close();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

我相信我正在创建动态线程来为每个连接的客户端提供服务,使用Global对象共享相同的数据源是不可能的,因为上面的run()主体对于每个连接的客户端都是完全相同的,因此消费者和生产者都是同样的方法。 我应该做什么修复,以便我可以为每个连接创建动态线程,并仍然共享相同的对象。

您可能需要一个队列来在每个客户端之间进行通信 每个队列将是从一个客户端推送到另一个客户端的数据的“管道”。

您会像这样使用它(伪代码):

Thread 1:
Receive request from Client A, with message for Client B
Put message on back of concurrent Queue A2B
Respond to Client A.

Thread 2:
Receive request from Client B.
Pop message from front of Queue A2B
Respond to Client B with message.

您可能还希望它是通用的,因此您拥有许多客户端(以及许多线程)可以写入的AllToB队列。

注意事项: ConcurrentLinkedQueueArrayBlockingQueue

如果要限制消息数,则ArrayBlockingQueue及其容量构造函数允许您执行此操作。 如果您不需要阻止功能,则可以使用方法offerpoll而不是puttake

我不担心共享队列,这会使问题变得更加复杂。 如果您知道需要解决的内存使用问题,请执行此操作。

编辑:根据您的更新:

如果需要在所有动态创建的实例之间共享单个实例,您可以:

  1. 创建一个静态实例。
  2. 将它传递给构造函数。

示例1:

public class ClientHandler extends Thread
{
  public static final Map<ClientHandler, BlockingQueue<String>> messageQueues 
    = new ConcurrentHashMap<>();

  <snip>

  public ClientHandler(Socket client)
  {
    super("ClientHandler");
    this.client = client;
    // Note: Bad practice to reference 'this' in a constructor.
    // This can throw an error based on what the put method does.
    // As such, if you are to do this, put it at the end of the method.
    messageQueues.put(this, new ArrayBlockingQueue<>());
  }

  // You can now access this in the run() method like so:
  // Get messages for the current client.
  // messageQueues.get(this).poll();
  // Send messages to the thread for another client.
  // messageQueues.get(someClient).offer(message);

几个笔记:

  • messageQueues对象应该包含客户端的某种标识符,而不是短暂的对象引用。
  • 更可测试的设计会将messageQueues对象传递给构造函数以允许模拟。
  • 我可能会建议为地图使用包装类,因此您可以使用2个参数调用offer,而不必担心映射语义。

暂无
暂无

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

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