以下代码是我的 TCP 服务器程序:
#包括
#包括
#pragma 注释 (lib,"ws2_32.lib")
#定义端口 8888
#define 地址“127.0.0.1”
int main()
{
WSADATA wsock;
SOCKET listensocket,connectsocket;
SOCKADDR_IN seraddr,cliaddr;
int cliaddrsize=sizeof(cliaddr);
int nret=0;
char buf[100];
printf("init socket ...\n");
if(WSAStartup(MAKEWORD(2,2),&wsock)!=0)
{
printf("WSAStartup() failed %d\n",WSAGetLastError());
return 0;
}
printf("init successfully\n");
printf("create TCP socket...\n");
if((listensocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET)
{
printf("socket create failed %d\n",WSAGetLastError());
WSACleanup();
return 0;
}
printf("socket create successfully\n");
seraddr.sin_family=AF_INET;
seraddr.sin_addr.s_addr=inet_addr(ADDR);
seraddr.sin_port=htons(PORT);
if(bind(listensocket,(SOCKADDR *)&seraddr,sizeof(seraddr))==SOCKET_ERROR)
{
printf("bind failed %d\n",WSAGetLastError());
closesocket(listensocket);
WSACleanup();
return 0;
}
printf("bind successfully\n");
if(listen(listensocket,5)==SOCKET_ERROR)
{
printf("listen failed %d\n",WSAGetLastError());
closesocket(listensocket);
WSACleanup();
return 0;
}
printf("wait for a connection on port %d\n",PORT);
if(connectsocket=accept(listensocket,(SOCKADDR*)&cliaddr,&cliaddrsize)==INVALID_SOCKET) //accept
{
printf("accept failed %d\n",WSAGetLastError());
closesocket(listensocket);
WSACleanup();
return 0;
}
printf("get connection from %s : %d successfully\n",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));//NB 啊
closesocket(listensocket);
printf("wait to receive data...\n");
memset(buf,0,sizeof(buf));
while(1)
{
if(nret=recv(connectsocket,buf,sizeof(buf),0)==SOCKET_ERROR) //recv
{
printf("recv failed %d\n",WSAGetLastError());
closesocket(connectsocket);
WSACleanup();
return 0;
}
printf(buf);
printf("\n");
if(strncmp(buf,"exit",sizeof("exit"))==0)
{
printf("exit the loop\n");
break;
}
if(nret=send(connectsocket,buf,sizeof(buf),0)==SOCKET_ERROR)
{
printf("send failed %d\n",WSAGetLastError());
}
}
closesocket(connectsocket);
WSACleanup();
return 0;
}
And I use my network debugging assistent software to run as a TCP client. As follows:
I started my TCP server program, it went as follows:
(...cannot upload images...)
但是当我点击我的 TCP 客户端时,TCP 服务器出错了:dos 框显示:recv failed 10038
我的问题是为什么出错了?以及如何解决?