一:添加依赖环境ws2_32.dll
windows的网络编程是基于ws2_32.dll动态链接库提供的API,所以要再项目工程中添加ws的网络环境。添加方式1:项目属性-链接器-输入-附加依赖项。添加方式2:预编译头#pragma comment(lib,"ws2_32.lib")
服务器端步骤:
1/初始化网络环境
2/创建socket
3/绑定主机IP地址/端口号
4/监听指定的端口
5/接收客户端连接
6/发送消息给客户端
7/接收客户端消息
8/关闭socket/关闭网络
二:实现
1/实例网络接口 WSAStartup函数
2/创建套接字描述符 socket函数
3/绑定主机IP地址/端口号
4监听端口
5/接收客户端连接
6发送消息给客户端
7/接收客户端消息
完整代码:
int startServer()
{
WSADATA wsaData;
int ret = WSAStartup(MAKEWORD(2,2), &wsaData);
if (ret != 0)
{
WSACleanup();
return -1;
}
//创建文件描述符 sock
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock ==-1)
{
closesocket(sock);
WSACleanup();
return -1;
}
//绑定服务器IP/PORT
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons (8090);
addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.225");
ret = bind(sock, (sockaddr*)&addr, sizeof(addr));
if (ret == SOCKET_ERROR)
{
closesocket(sock);
WSACleanup();
cout << "绑定sock失败";
return -1;
}
//监听端口
ret = listen(sock, 5);
if (ret == SOCKET_ERROR)
{
WSACleanup();
cout << "监听sock失败";
return -1;
}
//接收来自client的链接
sockaddr_in cAddr;//用于存储client的IP/程序端口的结构体
int len = sizeof(cAddr);
while (1)
{
SOCKET csock = accept(sock, (sockaddr*)&cAddr, &len);
if (csock == -1)
{
WSACleanup();
return -1;
}
char* ip = inet_ntoa(cAddr.sin_addr);
printf("client's ip is:%s\n",ip);
//处理client发送的消息
char buf[] = "server";
while (true)
{
ret = recv(csock, buf, sizeof(buf), 0);
if (ret <= 0)
{
//printf("faild with error:&s",WSAGetLastError());
cout << "接收client消息失败";
WSACleanup();
break;
}
cout << buf << endl;
cout << "向client发送消息:";
cin.getline(buf, sizeof(buf));
int contentSize = send(csock,buf,sizeof(buf),0);
}
closesocket(csock);
}
closesocket(sock);
WSACleanup();
return 0;
}
int main()//int argc,char* argv[]
{
startServer();
return 0;
}