一、创建服务端
1、新建一个控制台应用程序,添加源文件server
2、添加代码框架
#include <iostream> #include<WinSock2.h> #pragma comment(lib,"ws2_32.lib")//包含库文件 int main() { return 0; }
3、初始化socket库
WSAData wd = { 0 }; WSAStartup(MAKEWORD(2, 2), &wd);//以2.2版本为例,参数后面为主版本号
4、通信
void TCPServer() { //创建socket SOCKET hSockser = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (hSockser == INVALID_SOCKET)//创建套接字失败 { return; } //绑定ip和端口 SOCKADDR_IN addrser = { 0 }; addrser.sin_family = AF_INET; addrser.sin_port = htons(8848); addrser.sin_addr.S_un.S_addr = INADDR_ANY;//任意地址 bind(hSockser, (SOCKADDR*)&addrser, sizeof(addrser)); //监听 listen(hSockser, 5);//处理客户端的数量 //等待接收客户端连接 printf("等待接收客户端连接。。\n"); SOCKADDR_IN addrClient = { 0 }; int len = sizeof(addrClient); SOCKET hSockClient= accept(hSockser, (SOCKADDR*)&addrClient, &len); printf("已经与客户端建立连接。。\n"); //通信 //服务器首先接受数据 char szBuff[256] = { 0 }; int nRecv = recv(hSockClient, szBuff, 256, 0); char* ip = inet_ntoa(addrClient.sin_addr); printf("%s:%s,%d", ip, szBuff, nRecv); //关闭 closesocket(hSockser); closesocket(hSockClient); }
5、卸载
WSACleanup();
二、创建客户端
1、新建一个空项目,添加cpp文件
2、添加代码框架
#include <iostream> #include<WinSock2.h> #pragma comment(lib,"ws2_32.lib")//包含库文件 int main() { return 0; }
3、初始化socket库
WSAData wd = { 0 }; WSAStartup(MAKEWORD(2, 2), &wd);//以2.2版本为例,参数后面为主版本号
4、通信
void TCPClient() { //创建socket SOCKET hSockclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (hSockclient == INVALID_SOCKET)//创建套接字失败 { return; } //连接服务器 SOCKADDR_IN addrser = { 0 }; addrser.sin_family = AF_INET; addrser.sin_port = htons(8848); addrser.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); connect(hSockclient, (SOCKADDR*)&addrser, sizeof(addrser)); //通信 //客户端首先发送数据 const char * szSend ="aiyou bucuo"; send(hSockclient, szSend ,strlen(szSend), 0); //关闭 closesocket(hSockclient); getchar(); }
5、卸载
WSACleanup();
6、运行结果