Java套接字聊天服务器出现消息问题

时间:2020-05-14 17:32:36

标签: java sockets concurrency locks reentrantlock

我目前正在开发一种在终端中具有java和套接字的聊天服务器,并且工作正常,我们可以发送消息和接收消息。 问题是如果我们正在写一个句子,而又收到另一条消息,它将打断正在写的消息,例如:

scope :with_votes, -> do
  select( <<~SQL )
    (
      SELECT COUNT(*)
      FROM votes
      WHERE votable_type = '#{self.class.name}' AND 
            votable_id = '#{self.table_name}.id'
    ) AS votes
  SQL
end

我使用单独的线程读取传入的消息并编写新的消息,我可以使用可重入锁来避免在编写消息时接收消息吗?

发送消息代码:

   ClientA is writing "hello World"
   ClientB ,before ClientA can send his message, send his own "hello there"
   ClientA gets the result "hello Worldhello there" in its terminal, instead of being able to send his message and than receiving ClientB message.

读取消息代码:

while((userInput = systemIn.readLine()) != null && !userInput.equals("quit")) 
            {
                    out.println(userInput);
                    out.flush();
            }

0 个答案:

没有答案
相关问题