#include <winsock2.h> #include <stdio.h> #include <stdlib.h> #pragma comment(lib,"ws2_32.lib")//增加几个相关lib库
#define DEFAULT_PORT 5150 #define DEFAULT_BUFFER 4096
int main(int argc,char **argv) { WSADATA wsd; SOCKET sListen, sClient; int iAddrSize, ret; struct sockaddr_in local, client; char szBuff[DEFAULT_BUFFER];
if(WSAStartup(MAKEWORD(2,2), &wsd)!=0) { printf("Failed to load Winsock!\n"); return 1; } sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); if(sListen == SOCKET_ERROR) { printf("%d\n", WSAGetLastError()); }
local.sin_addr.s_addr = htonl(INADDR_ANY); local.sin_family = AF_INET; local.sin_port = htons(5000);
if(bind(sListen, (struct sockaddr *)&local, sizeof(local))==SOCKET_ERROR) { printf("%d\n", WSAGetLastError()); return 1; } listen(sListen, 8);
while(1) { iAddrSize = sizeof(local); sClient = accept(sListen, (struct sockaddr *)&local, &iAddrSize); if(sClient == INVALID_SOCKET) { printf("%d\n", WSAGetLastError()); break; }else{ ret = recv(sClient, szBuff, DEFAULT_BUFFER, 0); if(ret==0) break; else if(ret == SOCKET_ERROR) { printf("%d\n", WSAGetLastError()); break; }else{ szBuff[ret]='\0'; printf("RECV:%s", szBuff); }
} } closesocket(sListen); WSACleanup(); return 0;
}
|