I have a client and a server. I use UDP. (C/Unix)
In server I do have a structure:
typedef struct Header {
int seqid;
int len;
char payload[100];
}
...
char test[100];
struct Header package;
package.seqid = 1;
package.len = 64;
strcpy(package.payload, test);
sendto(sockfd, &package, 100, 0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));
In client I do have the same structure:
struct Header* myrepos;
...
recvfrom(sockfd, recvline, 100, 0, NULL, NULL);
//recvline is a char[100]
...
I want to load into the "myrepos" the submitted structure (submitted by server). How can I do that?
Using a
*angel = (struct Header*)&recvline;
result in compiler errors.
I am not sure if my methid is quite right or it can happen. Are there other solutions?
Thank You!
1: sendto(sockfd, &package, sizeof(struct Header), 0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));
2: recvline = new char [sizeof(struct Header)];
3: myrepos = (struct Header *)recvline;
I guess you are having a couple of problems here.
So, my suggestion is that you convert them all into a buffer and send it across and upon receiving decode the buffer to a structure.
Sample way of making a record for sending:
char sbuf[100] = {0};
char test[100] = {"Test Message"};
char *p = sbuf;
int bytestobesent = 0;
p = htonl(1);
p = p+sizeof(long);
p = htonl(64);
p = p+sizeof(long);
memcpy(p, test, strlen(test));
bytestobesent = sizeof(long) + sizeof(long) + strlen(test);
sendto(sockfd, sbuf, bytestobesent , 0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));
Just do the reverse of this, when you receive the buffer from the network. Hope this helps.
If you want to send fixed size packages. Then this could be the solution:
Server:
sendto(sockfd, &package, sizeof(package), 0,
(struct sockaddr*)&cliaddr, sizeof(cliaddr));
Client:
struct Header myrepos;
...
recvfrom(sockfd, &myrepos, sizeof(myrepos), 0, NULL, NULL);
Of cource you must check return codes of functions.
If you want to send variable sized packages, it would be more complex.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.