network parsing

Started by
9 comments, last by Brandisco 22 years, 8 months ago
Ouch. It looks like you've got much to learn...

First of all, what on earth do you need volatile for? I've never ever seen it used it any real program (well, in DOS times when you used to trap IRQs...).

Second, why do you send the messages as text? It'd be much easier to send them in binary form using something like this:

  // Somewhere in a header far, far awaytypedef struct { int type;} generic_packet_t;typedef struct { int type; int ex1; int ex2; int ey1; int ey2;} position_packet_t;#define PACKET_TYPE_POSITION 42// The send code:position_packet_t pkt;pkt.type = PACKET_TYPE_POSITION;// ADD: fill in pkt.ex1 .ex2 .ey1 and .ey2if (send(your_socket, &pkt, sizeof(pkt), 0) == -1) { // ADD: Error handling}// The receiver code:char buf[MAX_PACKET_SIZE];if (recv(your_socket, &buf, sizeof(buf), 0) == -1) { // ADD: Error handling}switch(((generic_packet_t *)&buf)->type) {case PACKET_TYPE_POSITION: position_packet_t *pkt = (position_packet_t *)&buf // alias // Read out .ex1, .ex2, etc.. here break; // ADD: Other packet typesdefault: // ADD: Error: Unknown packet}  


Of course this is a bit simplified, typed out of my head with potential errors and everything.
Oh, one _VERY_ important thing: Simply using recv() like is showed in this example is a very Bad Thing(tm). You should really save the buffer in between several recv()s, as a packet could've been split up - if you use TCP that is.
If you were using UDP, you'd have to use sendto() instead of send(), and recvfrom() instead of recv(). Packets can't be split in UDP, but they might get dropped, so UDP has its own difficulties.

Now if you do want to parse text (you will have to some time anyway), I'd give you a hint: Use some kind of tokenizer. Say you've read your packet into a string. Now write a function which scans this string for ':'s (just cycle through the string using pointers), replace those ':'s by 0s (not '0', an integer 0 which terminates a string) but save the starting pointer of each part (token) of the string. You'll end up with something similar to argc/argv in main(), which is quite easy to process.

To convert strings into integer, use atoi() or strtol(). Just look them up in the manual or online help or whatever you've got near you.

cu,
Prefect

One line of sourcecode says more than a thousand words.

Edited by - Prefect on August 16, 2001 1:03:59 PM
Widelands - laid back, free software strategy

This topic is closed to new replies.

Advertisement