#define WIN32_LEAN_AND_MEAN #define _WINSOCK_DEPRECATED_NO_WARNINGS #include<iostream> #include<stdio.h> #include<Windows.h> #include<WinSock2.h> //#pragma comment(lib,"ws2_32.lib")// win 写法 + 动态库 using namespace std; int main() { WORD ver = MAKEWORD(2, 2); WSADATA data; WSAStartup(ver, &data); //socket 网络通信 代码 //tcp 服务端 //1. 建立一个socket SOCKET _sock= socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //2.绑定用于客户端接收的网路端口 sockaddr_in _sin = {}; _sin.sin_family = AF_INET; _sin.sin_port = htons(4567); _sin.sin_addr.S_un.S_addr = htonl(INADDR_ANY);// inet_addr("127.0.0.1");//服务器 要绑定的ip地址 if (SOCKET_ERROR == bind(_sock, (sockaddr*)&_sin, sizeof(_sin))) { printf("bind error"); } else { printf("bind successful"); } //3.监听端口 if (SOCKET_ERROR == listen(_sock, 5)) { printf("listen error"); } else { printf("listen successful"); } //4。accept 等待接收客户连接 sockaddr_in _clientAddr = {}; SOCKET _cSock ; char msgbuf[] = "hello world"; int _cSock_Strlen = strlen(msgbuf) + 1; int len = sizeof(_clientAddr); //_cSock = accept(_sock, (sockaddr*)&_clientAddr, (int*)sizeof(_clientAddr)); //会返回客户端地址 while (true) { _cSock = accept(_sock, (sockaddr*)&_clientAddr, &len); //会返回客户端地址 if (INVALID_SOCKET == _cSock) { printf("INVALIE client socket"); } printf("new client:IP=%s ", inet_ntoa(_clientAddr.sin_addr)); //5。send 发送一条数据 send(_cSock, msgbuf, _cSock_Strlen, 0); } //6. 关闭socket closesocket(_sock); WSACleanup(); return 0; }
#define WIN32_LEAN_AND_MEAN #define _WINSOCK_DEPRECATED_NO_WARNINGS #include<iostream> #include<stdio.h> #include<Windows.h> #include<WinSock2.h> //#pragma comment(lib,"ws2_32.lib")// win 写法 + 动态库 using namespace std; int main() { WORD ver = MAKEWORD(2, 2); WSADATA data; WSAStartup(ver, &data); //socket 网络通信 代码 //tcp 服务端 //1. 建立一个socket SOCKET _sock= socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //2.绑定用于客户端接收的网路端口 sockaddr_in _sin = {}; _sin.sin_family = AF_INET; _sin.sin_port = htons(4567); _sin.sin_addr.S_un.S_addr = htonl(INADDR_ANY);// inet_addr("127.0.0.1");//服务器 要绑定的ip地址 if (SOCKET_ERROR == bind(_sock, (sockaddr*)&_sin, sizeof(_sin))) { printf("bind error"); } else { printf("bind successful"); } //3.监听端口 if (SOCKET_ERROR == listen(_sock, 5)) { printf("listen error"); } else { printf("listen successful"); } //4。accept 等待接收客户连接 sockaddr_in _clientAddr = {}; SOCKET _cSock ; char msgbuf[] = "hello world"; int _cSock_Strlen = strlen(msgbuf) + 1; int len = sizeof(_clientAddr); //_cSock = accept(_sock, (sockaddr*)&_clientAddr, (int*)sizeof(_clientAddr)); //会返回客户端地址 while (true) { _cSock = accept(_sock, (sockaddr*)&_clientAddr, &len); //会返回客户端地址 if (INVALID_SOCKET == _cSock) { printf("INVALIE client socket"); } printf("new client:IP=%s ", inet_ntoa(_clientAddr.sin_addr)); //5。send 发送一条数据 send(_cSock, msgbuf, _cSock_Strlen, 0); } //6. 关闭socket closesocket(_sock); WSACleanup(); return 0; }