我已经尝试、调试和哭了几个小时,希望让我的程序正确发送/打包和接收/解包我的数据。我唯一的希望是一些好的帮助!
为了打包/解包数据,我实现了 Beej 的网络编程指南 示例 pack2.c
代码工作包/解包在同一程序内部工作。但是,当我尝试通过套接字将打包数据发送到同一台计算机上的另一个程序时,它将无法正常工作!我的想法是 recv() 和 send() 函数在某种程度上可能会使数据损坏或类似的东西,我试图调试这是几种方法:
我需要一些帮助才能使其正常工作,我认为问题在于发送和接收 buf 的方式,因为 pack()/unpack() 函数在程序内部工作。
谢谢
客户端:
unsigned char buf[1024];
int16_t packetsize = pack(buf, "h", (int16_t)37);
packi16(buf+1, packetsize);
int len = packetsize;
uint16_t header = htons(packetsize); //Convert from host -> network
//Sends info to receiver about next pack coming.
printf("HEADER SIZE %d\n", packetsize);
if(send(sock, &header, packetsize, 0) == -1) {
perror("sendall");
}
/*==========SEND PACKAGE======================*/
int bytessendt = send(sock, buf, len, 0);//server_send_all(sock, buf, &len);
if(bytessendt == -1) {
perror("sendall");
}
printf("BYTES SENT OVER SOCKET: %d \n", bytessendt);
close(sock);
服务器端:
uint16_t buf;
int len = sizeof(buf);
if(recv(i, &buf, len, 0) == -1) {
printf("****Error when receiving");
}
int header = ntohs(buf);
printf("HEADER SIZE: %d\n", header);
/*========REICIVE PACK AND UNPACK================*/
unsigned char buf2[1024];
int16_t monkeycount;
int bytesreaded = recv(i, buf2, header, 0);
if(bytesreaded == -1) {
printf("Feil ved mottakelse\n");
}
printf("BYTES READED: %d\n", bytesreaded);
printf("BYTES SHOULD BE READED: %d\n", header);
unpack(buf2, "h", &monkeycount);
printf("CONTENT: %d\n", monkeycount);
close(i);
int server_send_all(int socket, unsigned char *buf, int *len) {
int total = 0; //Total amout of data to send
int bytesleft = *len; //Amount of data left to send
int n; //Holds return from send()
printf("SOCKET -DATA TO SEND: %d\n", *len);
while(total < *len) {
n = send(socket, buf+total, bytesleft, 0);
if(n == -1) { //send() returns error
break;
}
total += n;
bytesleft -= n;
}
*len = total; //Returns actually sent
return n == -1?-1:0;
}
发送字符串
来自客户:
int packetsize = 0;
packetsize += pack(buf + packetsize, "h", (int16_t)37);
packetsize += pack(buf + packetsize, "s", "Hello World");
send(sock, &header, packetsize, 0)
到服务器:
char s2[30];
unpack(buf2, "h30s", &monkeycount, s2);
printf("CONTENT: %d %s\n", monkeycount, s2);
给出输出
内容:37 你好,工作