[英]Socket data sending right but receiving altered
我有一個同時連接到兩台服務器的客戶端程序。 為了序列化我通過 sockets 傳輸的數據,我創建了以下struct
:
typedef struct {
char origin[14];
char type;
char data[100];
}socket_data;
當客戶端進程連接到服務器時,客戶端發送一些信息並等待接收兩個服務器的響應:
客戶:
//...
//Sending info to both servers
socket_data station_info;
strcpy(station_info.origin, "DANNY");
station_info.type = 'C';
strcpy(station_info.data, config.station);
write(socket_jack, &station_info, sizeof(socket_data));
write(socket_wendy, &station_info, sizeof(socket_data));
//Getting servers response
socket_data response_jack, response_wendy;
read(socket_jack, &response_jack, sizeof(socket_data));
read(socket_wendy, &response_wendy, sizeof(socket_data));
/*DEBUGGING*/char str[150]; sprintf(str, "%s, %c, %s\n", response_jack.origin, response_jack.type, response_jack.data);write(1, str, strlen(str));
/*DEBUGGING*/char st[150]; sprintf(st, "%s, %c, %s\n", response_wendy.origin, response_wendy.type, response_wendy.data);write(1, st, strlen(st));
//...
服務器 1 和服務器 2(兩者的代碼相同):
//...
//Receiving clients info
socket_data station_info;
read(socket, &station_info, sizeof(socket_data));
//Sending a response to the client
if (station_info.type != 'C') {
socket_data response;
strcpy(response.origin, "JACK");
response.type = 'E';
strcpy(response.data, "ERROR");
write(socket, &response, sizeof(socket_data));
close(socket);
return 0;
} else {
socket_data response;
strcpy(response.origin, "JACK");
response.type = 'O';
strcpy(response.data, "CONNECTION OK");
/*DEBUGGING*/char str[150]; sprintf(str, "%s, %c, %s\n", response.origin, response.type, response.data); write(1, str, strlen(str));
write(socket, &response, sizeof(socket_data));
}
如您所見,我添加了一些用於調試目的的writes
,當我執行代碼時,我期望在客戶端的理想 output 是:
JACK, O, CONNECTION OK
WENDY, O, CONNECTION OK
但相反,我得到了類似的東西:
, C, TION OK
WENDY, O, CONNECTION OK
或者
JACK, O, CONNECTION OK
, C, TION OK
有時它甚至不會打印任何東西。
我猜需要清除套接字緩沖區,但我不確定這是否是這里的解決方案。 如何解決此問題或清除套接字緩沖區?
作為上述評論的一個例子。
socket_data station_info;
char *buf = (char*) &station_info;
size_t len = sizeof(socket_data);
while (len > 0) {
ssize_t res = read(socket_jack, buf, len); //or write
if (res == -1) {
printf("io error.\n");
exit(-1); //only for test purpose, will exit the program here
}
buf += res; //increase the buffer position
len -= res; //decrease the remaining number of bytes
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.