简体   繁体   中英

Send other data types in winsock2

The send function in winsock2 accepts only char pointers. How do I send integers or objects through it too?

const char *buf which you need to pass to send() function as an argument is just a pointer to array of bytes. You need to convert integers to bytes:

const int MAX_BUF_SIZE = 1024;
int int_data = 4;
const char *str_data = "test";

char *buf = (char*) malloc(MAX_BUF_SIZE);
char *p = buf;

memcpy(&int_data, p, sizeof(int_data));
p += sizeof(int_data);

strcpy(p, str_data);
p += strlen(str_data) + 1;

send(sock, buf, p - buf, 0);

free(buf);

and reading code:

const int MAX_BUF_SIZE = 1024;
int int_data = 0;
const char *str_data = NULL;

char *buf = (char*) malloc(MAX_BUF_SIZE);
char *p = buf;

recv(sock, buf, MAX_BUF_SIZE, 0);

memcpy(p, &int_data, sizeof(int_data));
p += sizeof(int_data);

str_data = malloc(strlen(p) + 1);
strcpy(str_data, p);
p += strlen(p) + 1;

free(buf);

and complex objects needs to be serialized to stream of bytes.

Note 1: The code sample is valid iff both server and client use the same platforms (x32 / x64 / ...) that means int has the same amount of bytes and byte order is the same.

Note 2: Writing code should check that there is no buffer ( MAX_BUF_SIZE ) overflow on each step.

Just store the value into a variable and then type-cast the variable to char* . The send() and recv() functions operate on binary data, despite taking char* parameters.

Sending:

int int_data = 4;
send(sock, (char*) &int_data, sizeof(int), 0);

Reading:

int int_data;
recv(sock, (char*) &int_data, sizeof(int), 0);

Generally, the easiest way is to print the integer or object to a string, and send that string. Textual representations are more portable, and also easier to debug.

std::stringstream may be a useful class both to create the string and parse it on the other end.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM