开发者

What should a socket-based protocol look like for a C daemon?

开发者 https://www.devze.com 2023-02-02 09:40 出处:网络
I am writing a C daemon which my web application will use as a proxy to communicate with FTP servers. My web application enables users to connect and interact with FTP sites via AJAX. The reason I nee

I am writing a C daemon which my web application will use as a proxy to communicate with FTP servers. My web application enables users to connect and interact with FTP sites via AJAX. The reason I need a C daemon is that I have no way of keeping FTP connections alive across AJAX calls.

My web application will need to be able to tell my daemon to do list, get, put, delete, move, and rename files to a given FTP server for a given user account. So when my application talks to the daemon, it needs to pass the following via some protocol I define: 1) action, 2) connection id, 3) user id, 4) any additional parameters for action (note: connection information is stored in a database, so the daemon will talk to that as well).

So that's what I need my daemon to do. I'm thinking communication between my web app and the daemon will take place via a TCP socket, but I don't know exactly what data I would send. I need an example. For instance, should I just send something like this over the socket to the daemon?

action=list&connection_id=345&user_id=12345&path=/some/path

or should I do something hardcore at the byte level, like this?

+-----------------+-------------------------+------------开发者_运维百科-------+-----------------------------------+
| 1 byte (action) | 4 bytes (connection id) | 4 bytes (user id) | 255 bytes (additional parameters) |
+-----------------+-------------------------+-------------------+-----------------------------------+
| 0x000001        | 345                     | 12345             | /some/path                        |
+-----------------+-------------------------+-------------------+-----------------------------------+

What does such communication over a socket normally look like?


Really it's mostly about whatever format is easiest for you to encode and parse, which is why rather than reinventing the wheel with my own protocol, I personally would go with an existing remote procedure call solution. My second choice would be the bitfields, as that's easy to pack into and out of a struct.


You don't necessarily need to implement your own protocol. Have you thought about using something like XML-RPC, or even just plain XML? There are C libraries that should let you parse it.


Binary protocols are a bit easier to deal with. Just prepend the length to the message (or just the variable part of it) - TCP doesn't know about your application-level message boundaries. Pay attention to number endianness.

On the other hand, text-based protocols are more flexible.

Also, take a look at Google Protocol Buffers - could be very useful, though I'm not sure ajax is supported.

0

精彩评论

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

关注公众号