Windows Socket 编程:TCP服务器端

时间:2022-01-31 05:12:14

#include <stdio.h>

#include <stdlib.h>

#include <winsock2.h>


int main(int argc,char* argv[])

{

int szClntAddr;

char message[] = "hello szt!~\n";


WSADATA wsaData;

SOCKET hServSock,hClntSock;

SOCKADDR_IN servAddr,clntAddr;


WSAStartup(MAKEWORD(2,2),&wsaData);


hServSock = socket(PF_INET,SOCK_STREAM,0);


memset(&servAddr,0,sizeof(servAddr));

servAddr.sin_family = AF_INET;

servAddr.sin_addr.s_addr = htonl(INADDR_ANY);

servAddr.sin_port = htons(atoi(argv[1]));


bind(hServSock,(SOCKADDR *)&servAddr,sizeof(servAddr));

listen(hServSock,5);


szClntAddr = sizeof(clntAddr);

hClntSock = accept(hServSock,(SOCKADDR *)&clntAddr,&szClntAddr);


send(hClntSock,message,sizeof(message),0);


closesocket(hServSock);

closesocket(hClntSock);


WSACleanup();


return 0;

}


Windows Socket 编程:TCP服务器端