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

时间:2012-06-08 06:09:10

标签: java multithreading sockets

我在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()的主体对于每个客户端都是完全相同的连接,因此同样的方法是消费者和生产者。我应该做什么修复,以便我可以为每个连接创建动态线程,并仍然共享相同的对象。

1 个答案:

答案 0 :(得分:5)

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

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

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. 将其传递给构造函数。
  3. 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个参数的商品,而不必担心地图语义。
相关问题