Question

I have a assignment where I am going to implement a score-server for a game. When a game is done the game is going to send() players name (char *name) and score (int score) to the server for registration, receive(), and the server is going to send back 5 top-scores.

We are going to use Berkeley sockets and C. After some reading and studying of examples I can only find examples that just sends single variables.

write(sd, "Hello World", 12);

char buf[13];
read(sd, buf, 12);
buf[12] = '\0';

What is usual to do ? Send each variable (name and score) is separate write() functions, or create a struct that holds both variables ?

After some reading in Beej's Guide to Network Programming I come across the problem with byte order(big/little -endian) that I must take in account, this is shown under the section 7.4 Serialization - How to pack data, and is OK except that in all sample code packages they float and single variables, is there any way to pack an entire struct ?

There is also a section 7.5 Sone of Data Encapsulation that takes about creating a protocol that describes how a client and server communicates, for me this looks more like a struct and what I wont to do, but there is no code that shows the principle.


In short: I want to create a stable communication between server and client where I exchange more than just single variables,

Was it helpful?

Solution

In network communication, there is no concept of variables, or structs. What you are doing is sending a sequence of bytes.

So the idea of sending structs, is the same as sending a single value: Convert the struct into a sequence of bytes (serialization), write it to the socket, and on the other end, convert the sequence of bytes back into a struct (deserialization).

So now your problem becomes one of serialization: How do I serialize a struct?

Which is just the composition of serializing individual values of the struct.

What is more common

typically you want to reduce the amount of network traffic. So if you have all the data you want to send upfront, sending it at once is going to be more efficient then manually chunking the data by sending each name/score pair separately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top