//六步创建TCP服务端
#include<iostream>
#include<Windows.h>
using namespace std;
int main()
{
//初始化ws2_32.dll
WORD ver = MAKEWORD(2, 2);
WSADATA wsaData;
WSAStartup(ver, &wsaData);//对应WSACleanup的调用
//1.建立一个socket
SOCKET _sock = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (_sock == INVALID_SOCKET)
{
cout<<"创建socket失败" << endl;
WSACleanup();
return 0;
}
else
{
cout << "创建socket成功" << endl;
}
//填充sockaddr_in结构
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(1234);
sin.sin_addr.S_un.S_addr = INADDR_ANY;
//2.绑定端口
if (bind(_sock, (sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR)
{
cout << "绑定端口失败" << endl;
WSACleanup();
return 0;
}
else
{
cout << "绑定端口成功" << endl;
}
//3.Listen监听网络端口
if (listen(_sock, 10) == SOCKET_ERROR)
{
cout << "监听端口失败" << endl;
WSACleanup();
return 0;
}
else
{
cout << "监听端口成功" << endl;
}
//4.accept等待客户端连接
sockaddr_in clientAddr;
int nAddrLen= sizeof(clientAddr);
SOCKET client;
char buf[] = "Hello,I am Server.";
while (true)
{
client = accept(_sock, (sockaddr*)&clientAddr, &nAddrLen);
if (client == INVALID_SOCKET)
{
cout << "接受到无效客户端" << endl;
WSACleanup();
return 0;
}
else
{
cout << "接受客户端连接成功" << endl;
}
cout << "新客户端连接IP: " << inet_ntoa(clientAddr.sin_addr) << endl;
//5.send向客户端发送一条数据
send(client, buf, strlen(buf) + 1, 0);
}
//6.关闭套接字closesocket
closesocket(client);
closesocket(_sock);
//清楚windows socket环境
WSACleanup();
system("pause");
return 0;
}