开发者

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

开发者 https://www.devze.com 2023-03-27 03:25 出处:网络
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 conversat开发者_JAVA百科i

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 conversat开发者_JAVA百科ion. 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号