Search code examples
c#socketsserversocket

Writing socket server for existing socket client


I am new to Socket programming. We have to write socket server for existing c# socket client. Protocol is TCP, no TLS. The server code is not available. How to ensure that server socket component will respond to Client call? What are the important things that I need to be aware of? Someone from the team was saying that I need to implement the same protocol that existing server was using. what does that mean?


Solution

  • Sockets are just a mechanism to exchange bytes; exchanging bytes is relatively easy - but what you need to know is what bytes to send (and when receiving: what those bytes mean). This is the wire protocol.

    The first thing you need to figure out is the raw transport details: is this TCP? UDP? what port number? is there TLS involved? etc. UDP is a packet protocol, TCP is a stream protocol, but in either case you need to find out how messages are represented on that protocol. If this is a well-known protocol, there may be a specification you can read - or even better: a prebuilt implementation. But essentially you're looking for details like this (RFC6455, web-sockets) or this (RESP===redis). The first thing this will usually define is the framing - for example in UDP, it could be as simple as "1 packet===1 frame, maxiumum SOME_NUMBER bytes", but in TCP it is more likely to be something like "frames are prefixed by a header of 14 bytes; the 3rd-7th bytes of that header denote the payload length as a little-endian 32-bit integer; the header is followed by the PAYLOAD_LENGTH bytes" - or similar. For a text-focused protocol, it could be "frames termination is 2 end-of-line sequences, accepting (some specified combination/permutation of CR/LF). Note further that the message's protocol might not include the data serialization protocol; it might be as simple as "payloads are UTF-8 encoded text", but it might be "payloads are protobuf messages following SomeUnknown.proto", or something entirely bespoke and undocumented. It may even not be defined strictly (for example, gRPC usually assumes that it is talking protobuf, but that is not strictly required). Other common formats might be JSON or XML, but raw sockets are often more binary than text.