我正在尝试制作一个异步 UDP 聊天应用程序,目前只有一个客户端和服务器。
当我运行我的服务器时,会显示很多冗余数据。之后,当输入一些文本时,
发送文件时出错!
被展示。
有人可以看看代码,让我知道我哪里出错了吗?
服务器:
u_long iMode=1;ioctlsocket(sd,FIONBIO,&iMode); 诠释n=sd+1;
fd_set readfds,writefds;
while(1)
{
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_SET(sd,&readfds);
FD_SET(sd,&writefds);
int rv = select(n, &readfds, &writefds, NULL, NULL);
if(rv==-1)
{
printf("Error in Select!!!\n");
exit(0);
}
if(rv==0)
{
printf("Timeout occurred\n");
}
if (FD_ISSET(sd, &readfds))
{
FD_CLR(sd,&readfds);
int client_length = (int)sizeof(struct sockaddr_in);
memset(&buffer,0,sizeof(buffer));
int bytes_received = recvfrom(sd, buffer,SIZE, 0, (struct sockaddr *)&client, &client_length);
if (bytes_received < 0)
{
fprintf(stderr, "Could not receive datagram.\n");
closesocket(sd);
WSACleanup();
exit(0);
}
}
printf("\nClient says: %s",buffer);
printf("\nWrite :");
fgets(buffer,SIZE,stdin);
if(FD_ISSET(sd,&writefds))
{
FD_CLR(sd,&writefds);
int client_length = (int)sizeof(struct sockaddr_in);
if(sendto(sd, buffer,strlen(buffer), 0, (struct sockaddr *) &client,client_length)<0)
{
printf("Error sending the file! \n");
exit(1);
}
}
}
closesocket(sd);
WSACleanup();
return 0;
}