开发者

Client / Server conversation - am I doing it wrong?

开发者 https://www.devze.com 2023-03-26 21:04 出处:网络
I have a client/server application that I made using sockets. The thing is, when I send a command requesting some information and wait for a reply I block untill that reply comes. This makes it harder

I have a client/server application that I made using sockets. The thing is, when I send a command requesting some information and wait for a reply I block untill that reply comes. This makes it harder to implement bidirecional requesting/responde. Let me explain using one example: The client can list files in a directory of the server, so I do someting like that in code:

Client code: 1- Send request command: LS / 2- Blocks waiting for the LS responde. 3- Get the file list.

The reason why I did that is that the Client may have to transfer a file, so I do: 1- Send request for transfering a file. 2- Blocks on read() waiting to see if the server accepts 3- Only if it does, send the file.

So it was fine untill 开发者_运维知识库I had to add the server the ability to request anything. In my code, the client can request anything and get blocked waiting for a response. The server might then send any request command that will make no sense for the responde the client is waiting for. This would screw the conversation.

One resolution I tought is to never block for a response. I would send a request command, and then come back to wait for ANY request or response from the server, if a response arrives then I would send the file. So the thing is will I have to add like an ID in each request/response pair to know which response is for which request?

PS: Im pretty lost in how to design a network conversation between hosts and have never read a book about desing patterns for network applications.

PS2: sry my bad english ;)


The thing you are looking for is an application-level protocol between the server and the clients.

For your particular case the simplest way is for the server to say upfront what it is going to send next. Say, put a message type byte in front of the message. Say 0 means request, 1 means response, etc. Stick that into a switch statement and you are done.

It's a good idea to include message length in that header too, so the receiving code knows how many bytes to fetch from the network to get a complete message.

0

精彩评论

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