Hi,
I am creating an UDP client for an UDP server. My UDP client sends some information like id, name and age, etc and the UDP server saves that information in an array. When the client wants to retrieve information, it sends the id, and the server replies back with name and age. Fun stuff.
I am using two structs. I created one structure for the datagram that carries the information. Code for the datagram is as follows:
1 2 3 4 5
|
typedef struct {
TYPE type; // Type of this datagram
unsigned int seq; // Sequence number of this datagram
char data[ MAX_DATA ]; // The data itself (if any).
} Datagram;
|
The second structure is my data record structure that carries the information such as name, id, age, and command (for adding or retrieving from server). Below is the code:
1 2 3 4 5 6 7
|
struct Data_Record {
int command; // 0 for add, 1 for retrieve
// 0 for sucess, 1 for failure
int id; // sequence number
char name[32]; // Name
int age; // Age
};
|
So basically the plan is to send seq number, data type (ACK, SYN, FIN) in datagram while, passing the Data_Record into datagram.data and send the datagram to the server which pulls information from datagram.data.
While sending data to server, I can see my program working properly (the server shows me the data I send which matches up). My code while sending is as follows:
datasend = datagram,
dr = data_record
1 2 3 4 5
|
datasend.seq = seq;
datasend.type = DATA;
memcpy(datasend.data, &dr, sizeof(dr));
sendto( s, (char *)&datasend, sizesend, 0,
(struct sockaddr *)&server, sizeof(server));
|
But while receiving information from the server, my program doesn't seem to get the right information back. The code for receiving is as follows:
1 2 3 4 5 6
|
int from_len = sizeof(server);
int sizereceive = sizeof(datasend);
serversays = recvfrom(s, (char *)&datasend, sizereceive, 0,
(struct sockaddr *)&server, &from_len);
memcpy(&dr, datasend.data, sizeof(datasend.data));
|
Now, when I want to retrieve information, I enter the id that I want to retrieve and the server sends me that information corresponding to the ID. So, the data already exists with id = 1, name = tom, age = 22, and when I want to retrieve, I send the ID to be retrieved as "1" and server should send me "tom" and "22". But in my case, when I enter the id, for example, "1", the server on it's console displays the right information "1, tom, 22", but the client shows me as id = "1", name = blank, age = blank. Now, if I persistently ask for id 1 two more times, only then it shows me "1, tom, 22" in 3rd attempt to retrieve the same ID.
Can someone tell me what I am doing wrong? Is something wrong with my recvfrom code?