【发布时间】:2018-10-19 18:45:25
【问题描述】:
我创建了一个UDP客户端/服务器通信为了测试发送wav文件,客户端每次发送一个2048个文件样本的缓冲区到服务器。问题是,对于每个缓冲区,只有缓冲区的前半部分(1024 个样本)被正确发送,我无法弄清楚这个错误背后的原因。
这是客户端代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define SERVER "127.0.0.1"
#define BUFLEN1 512
#define BUFLEN2 2048
#define PORT 8888
void die(char *s)
{
perror(s);
exit(1);
}
int main(void)
{
struct sockaddr_in si_other;
int s, i, slen=sizeof(si_other);
char fileaddress[BUFLEN1];
short buf[BUFLEN2];
FILE *file;
int k;
if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
{
die("socket");
}
memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
if (inet_aton(SERVER , &si_other.sin_addr) == 0)
{
fprintf(stderr, "inet_aton() failed\n");
exit(1);
}
printf("Enter file address: ");
gets(fileaddress);
file=fopen(fileaddress,"rb");
while ((k = fread(buf, sizeof(short), BUFLEN2, file)) > 0) {
if (sendto(s, buf, BUFLEN2 , 0 , (struct sockaddr *) &si_other, slen)==-1)
{
die("sendto()");
}
}
close(s);
return 0;
}
服务器代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define SERVER "127.0.0.1"
#define BUFLEN2 2048
#define PORT 8888
void die(char *s)
{
perror(s);
exit(1);
}
int main(void)
{
struct sockaddr_in si_me, si_other;
int s, i, slen = sizeof(si_other) , recv_len;
short buf[BUFLEN2];
//create a UDP socket
if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
{
die("socket");
}
// zero out the structure
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
//bind socket to port
if( bind(s , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1)
{
die("bind");
}
printf("Waiting for data...\n");
fflush(stdout);
while(1)
{
recv_len = recvfrom(s, buf, BUFLEN2, 0, (struct sockaddr *) &si_other, &slen);
if (recv_len == -1)
{
die("recvfrom()");
}
}
close(s);
return 0;
}
【问题讨论】:
-
没有回答这个问题,但如果您正在传输文件,那么您很可能在使用 UDP 时出错。您应该考虑使用 TCP,它在数据损坏方面更安全。
标签: c sockets udp client-server