【问题标题】:Design(Classes, methods, interfaces) of real time applications(server/client)实时应用程序(服务器/客户端)的设计(类、方法、接口)
【发布时间】:2011-10-25 00:32:05
【问题描述】:

我一直在寻找有关此主题的好书或文章,但没有找到太多。对于特定场景,我没有找到一个很好的例子——一段代码。就像客户端/服务器对话。 在我的应用程序协议中,他们必须发送/接收消息。喜欢: 服务器想要向客户端发送文件 客户可以接受或不接受, 如果他接受,服务器将通过相同的连接/套接字发送字节。 我的应用程序的其余部分都使用阻塞方法,服务器有一个方法

这就是我所做的:

服务器方法:

public synchronized void sendFile(File file)
{
  //send messsage asking if I can send a file
  //block on read, waiting for client responde
  //if client answers yes, start sending the bytes
  //else return
}

客户端方法:

public void reciveCommand()
{
   //read/listen for a command from socket
   //if is a send file command handleSendFileCommand();
   //after the return of handleSendFileCommand() listen for another command
}

public void handleSendFileCommand()
{
   //get the file server want to send
   //check if it already has the file
   //if it already has, then send a command to the socket saying it already has and return         
   //else send a command saying server can send the file
   //create a FileInputStream, recive bytes and then return method
}

我 100% 确定这是错误的,因为服务器和客户端不可能双向对话,我的意思是,当服务器想要向服务器发送命令时,他们必须遵循命令的顺序,直到对话结束完成后,他们才能发送/接收另一个命令序列。这就是为什么我让所有发送请求的方法同步

我并没有花很多时间意识到我需要研究这种应用程序的设计模式...... 我阅读了有关责任链设计模式的信息,但我不明白如何在这种情况下使用它或其他好的设计模式。

我希望有人可以帮助我提供一些代码示例。 提前致谢

【问题讨论】:

    标签: java network-programming network-protocols


    【解决方案1】:

    synchronized Java 中的关键字意味着完全不同的东西——它将方法或代码块标记为critical section,一次只能执行单个线程。你在这里不需要它。

    然后,一个 TCP 连接 在字节流级别上是双向的。服务器和客户端之间的同步由交换的消息驱动。将客户端(几乎同样适用于服务器)视为state machine。某些类型的消息在当前状态下是可以接受的,有些不是,有些会将节点切换到不同的状态。

    由于您正在研究设计模式,State pattern 在这里非常适用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多