在winsock2中发送其他数据类型

Pil*_*pel 1 c++ windows tcp winsock2

winsock2中的send函数只接受char指针.如何通过它发送整数或对象?

dma*_*a_k 5

const char *buf你需要传递给send()函数作为参数只是一个指向字节数组的指针.您需要将整数转换为字节:

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);
Run Code Online (Sandbox Code Playgroud)

和阅读代码:

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);
Run Code Online (Sandbox Code Playgroud)

并且需要将复杂对象序列化为字节流.

注1:如果服务器和客户端使用相同的平台(x32/x64/...),则代码样本有效,这意味着int具有相同的字节数且字节顺序相同.

注2:编写代码应检查MAX_BUF_SIZE每一步都没有buffer()溢出.