【发布时间】: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