socket udp 服务端 客户端
tcp_server.cpp
#include <WinSock2.h> #include <iostream> using namespace std; #pragma comment(lib,"ws2_32.lib") int main() { //初始化winsock 环境 WSADATA wd; ; if (WSAStartup(MAKEWORD(2, 2), &wd) != 0) { cout << "WSAStartup error:" << GetLastError() << endl; return 0; } //1,创建UDP数据报 套接字 SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); //2,绑定到ip地址和端口 sockaddr_in addr; //网络字节序 addr.sin_port = htons(8000); //addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); addr.sin_addr.s_addr = inet_addr("127.0.0.1"); addr.sin_family = AF_INET; int len = sizeof(sockaddr); if (bind(s, (sockaddr*)&addr, len) == SOCKET_ERROR) { cout << "bind error:" << GetLastError() << endl; return 0; } int nNetTimeout = 5000; //接收时限 if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&nNetTimeout, sizeof(int)) == SOCKET_ERROR) { cout << "setsockopt error:" << GetLastError() << endl; return 0; } //3 接受或发送数据 int ret = 0; do { //接收 客户端地址 sockaddr_in addrClient; memset(&addrClient, 0, sizeof(addrClient)); //要赋值结构体的长度 int len = sizeof(sockaddr); char buf[100] = { 0 }; //默认是阻塞的,没有数据过来 会一直等待 ret = recvfrom(s, buf, 100, 0, (sockaddr*)&addrClient, &len); cout << "recvfrom " << len << ":" << buf << endl; ret = sendto(s, "i am server!", strlen("i am server!"), 0, (sockaddr*)&addrClient, len); } while (ret != SOCKET_ERROR && ret != 0); //4 关闭套接字 closesocket(s); //清理winsock2环境 WSACleanup(); return 0; //netstat -ao }
tcp_client.cpp
#include <WinSock2.h> #include <iostream> using namespace std; #pragma comment(lib,"ws2_32.lib") int main() { //初始化winsock 环境 WSADATA wd; ; if (WSAStartup(MAKEWORD(2, 2), &wd) != 0) { cout << "WSAStartup error:" << GetLastError() << endl; return 0; } //创建数据报socket SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (s == INVALID_SOCKET) { cout << "socket error:" << GetLastError() << endl; return 0; } //服务端的地址 sockaddr_in addr; addr.sin_addr.s_addr = inet_addr("127.0.0.1"); addr.sin_port = htons(8000); addr.sin_family = AF_INET; int len = sizeof(sockaddr_in); int ret = 0; do { //2, 可以sendto发送 和 recvfrom接受 ret = sendto(s, "i am client!", strlen("i am client!"), 0, (sockaddr*)&addr, len); char buf[100] = { 0 }; ret = recvfrom(s, buf, 100, 0, NULL, NULL); cout << "recvfrom" << ret << ":" << buf << endl; Sleep(1000); } while (ret != SOCKET_ERROR && ret != 0); //3关闭套接字 closesocket(s); //清理winsock2环境 WSACleanup(); return 0; //netstat -ao }