64,682
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <WinSock.h>
#define PORT 8516
#pragma comment(lib, "ws2_32.lib")
int main()
{
// 将此后注释掉,socket()会返回失败,但是perror并没有输出错误
/*
//initialize Winsock
WORD wVersion=MAKEWORD(2,0);
WSADATA wsData;
int nResult=0;
nResult=WSAStartup(wVersion,&wsData);
*/
SOCKET sockfd,newfd,numbytes;
int sin_size=sizeof(struct sockaddr_in);
char rev[100000];
sockaddr_in server,client;
server.sin_addr.s_addr=inet_addr("127.0.0.1");
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
memset(server.sin_zero,'0',8);
if((sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == -1)
{
perror("socket");// 输出 no error, 并没有输出错误,是什么原因?
}
int nRe=0;
if((nRe=bind(sockfd,(sockaddr *)&server,sizeof(struct sockaddr)))==-1) perror("bind");
if(listen(sockfd,10)==-1) perror("listen");
printf("正在监听端口%d中....\n",PORT);
while(1)
{
if((newfd=accept(sockfd,(sockaddr *)&client,&sin_size))==-1)
continue;
printf("已经与IP为%s的客户建立连接........\n",inet_ntoa(client.sin_addr));
if(numbytes=recv(newfd,rev,100000,0)==-1) perror("recv error");
printf("正在接受数据....\n");
rev[numbytes]='\0';
printf("数据已成功接收:\n%s",rev);
shutdown(newfd,2);
}
return 0;
}