Design(Classes, methods, interfaces) of real time applications(server/client)

邮差的信 提交于 2019-12-10 23:17:41

问题


I´ve been looking for a good book or article about this topic but didnt find much. I didnt find a good example - piece of code - for a specific scenario. Like clients/server conversation. In my application´s protocol they have to send/recieve messages. Like: Server want to send a file to a client Client can accpet or no, if he accepts, server will send bytes over the same connection/socket. The rest of my application all uses blocking methods, server has a method

Heres what I did:

Server method:

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
}

Client methods:

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
}

I am 100% sure this is wrong because, there is no way server and clients would talk bidirecional, I mean, when server wants to send a command to a server, they have to follow an order of commands until that conversation is finished, only then, they can send/recive another sequence of commands. Thats why I made all methods that send requests synchronized

It didnt took me a lot of time to realize I need to study about design patterns for that kind of application... I read about Chain of Responsibility design pattern but I dont get it how can I use it or another good design pattern in that situation.

I hope someone can help me with some code example-like. Thanks in advance


回答1:


synchronized keyword in Java means something completely different - it marks a method or a code block as a critical section that only single thread can execute at a time. You don't need it here.

Then, a TCP connection is bi-directional on the byte-stream level. The synchronization between the server and a client is driven by the messages exchanged. Think of a client (same pretty much applies to the server) as a state machine. Some types of messages are acceptable in the current state, some are not, some switch the node into different state.

Since you are looking into design patterns, the State pattern is very applicable here.



来源:https://stackoverflow.com/questions/7027121/designclasses-methods-interfaces-of-real-time-applicationsserver-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!