大家好,我对网络世界还很陌生,我已经编写了udp客户端-服务器程序。我发现困难的是如何在服务器完成数据发送后关闭客户端程序(.exe)。我当时在考虑使用recvfrom()的返回值,但这最终使程序无法控制最后打印的else节( 10054 失败)。这是我的客户端代码:-
#define _WIN32_WINNT 0x0501
#include<winsock2.h>
#include<stdio.h>
#include <dirent.h>
#include<string.h>
#define DEFAULT_PORT 27015
#define DEFAULT_BUFLEN 1400
#define DEFAULT_FLEN 25
#define DEFAULT_SERVER_ADDR "127.0.0.1"
int main(){
int iResult, bufflen = DEFAULT_BUFLEN,fLen = DEFAULT_FLEN;
SOCKET client_socket = INVALID_SOCKET;
WSADATA wsaData;
struct sockaddr_in server;
int sLen = sizeof(server);
char recvBuf[DEFAULT_BUFLEN] ="",filename[DEFAULT_FLEN] ;
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if(iResult != 0){
printf("WSAStartup failed : %d\n",WSAGetLastError());
return -1;
}
//creating unbound socket
client_socket = socket(AF_INET, SOCK_DGRAM, 0);
if(client_socket == INVALID_SOCKET){
printf("Error at socket(): %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
memset((char *) &server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(DEFAULT_SERVER_ADDR);
server.sin_port = DEFAULT_PORT;
printf("Enter filename :: ");
scanf("%[^\n]s",filename);
iResult = sendto(client_socket,filename,fLen,0,(struct sockaddr *)&server, sLen);
if(iResult == SOCKET_ERROR){
printf("sendto() failed with error code : %d" , WSAGetLastError());
return -1;
}
int sendno = 1,bytes_written = 0, ACK ;
memset(recvBuf,'\0',sizeof(recvBuf));
FILE *fp = NULL;
fp = fopen(filename,"ab");
while(iResult != -1){
iResult = recvfrom(client_socket, recvBuf, bufflen, 0, (struct sockaddr *) &server, &sLen);
if (iResult > 0){
ACK = sendto(client_socket,recvBuf,bufflen,0,(struct sockaddr *)&server, sLen);
printf("ACK Sent = %d\n",ACK);
printf("Byte(s) received :: %d iteration %d\n",iResult,sendno);
sendno++;
bytes_written = fwrite(recvBuf,sizeof(char),iResult,fp);
printf("bytes written %d\n",bytes_written);
memset(recvBuf,'\0',sizeof(recvBuf));
}
else if (iResult == 0){
printf("Connection closed\n");
break;
}
else{
printf("Recevied failed %d\n",WSAGetLastError());
}
}
//cleanup
closesocket(client_socket);
WSACleanup();
return 0;
}