WORD ver = MAKEWORD(2, 2); //创建WINDOWS版本号
WSADATA dat;
WSAStartup(ver, &dat); //启动网络环境,此函数调用了一个WINDOWS的静态链接库,因此需要加入静态链接库文件
//-----------------
//-- 用socket API建立简易TCP服务端
// 1 建立一个socket
SOCKET _sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
// 2 bind 绑定用于接收客户端连接的网络端口
sockaddr_in _sin = { };
_sin.sin_family = AF_INET;
_sin.sin_port = htons(4567);
_sin.sin_addr.S_un.S_addr = INADDR_ANY; //inet_addr("127.0.0.1");
if (SOCKET_ERROR == bind(_sock, (sockaddr*)&_sin, sizeof(_sin)))
{
cout << "错误,绑定网络端口失败..." << endl;
}
else {
cout << "绑定端口成功..." << endl;
}
// 3 listen 监听网络端口
if (SOCKET_ERROR == listen(_sock, 5))
{
cout << "错误,监听网络端口失败..." << endl;
}
else {
cout << "监听网络端口成功..." << endl;
}
// 4 accept 等待接收客户端连接
sockaddr_in _clientAddr = { };
int nAddrLen = sizeof(_clientAddr);
SOCKET _cSock = INVALID_SOCKET;
char msgBuf[] = "HELLO, I'm Server";
while (true)
{
_cSock = accept(_sock, (sockaddr*)&_clientAddr, &nAddrLen);
if (INVALID_SOCKET == _cSock)
{
cout << "错误,接收到无效客户端SOCKET..." << endl;
}
cout << "新客户加入:IP = " << inet_ntoa(_clientAddr.sin_addr);
// 5 向客户端发送一条数据
send(_cSock, msgBuf, strlen(msgBuf) + 1, 0);
// 6 关闭套接字closesocket
closesocket(_sock);
}
//-----------------
//清除Windows socket环境
WSACleanup(); //关闭Socket网络环境
return 0;
}
2021-07-07简易服务端(TCP)
最新推荐文章于 2021-08-12 13:11:29 发布