• 简单的socket通信


    //client
    #include <iostream> #include <WinSock2.h> #pragma comment(lib, "WS2_32") // 链接到WS2_32.lib using namespace std; int main() { SOCKET so; WSADATA ws; if (WSAStartup(MAKEWORD(2, 2), &ws) != 0) { cout << "WSAStartup failed" << endl; } if((so = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) { cout << "socket failed" << endl; } //绑定地址时需要将主机字节序转换成网络字节序,这个地址是需要连接的ip和端口 sockaddr_in addr = {0}; addr.sin_addr.s_addr = inet_addr("127.0.0.1");//此地址是网络字节序,需要将主机字节序抓换成网络字节序,inet_addr:可以转换ip地址 addr.sin_family = AF_INET; addr.sin_port = htons(2000); //addr.sin_zero if(connect(so, (sockaddr*)&addr, sizeof(sockaddr)) == SOCKET_ERROR)//connect,系统自动分配端口号和IP,无需自己绑定 { cout << "connect failed" << endl; } char sendBuf[4096]; while(1) { fgets(sendBuf, 4096, stdin); if(send(so, sendBuf, strlen(sendBuf), 0) < 0)//send { cout << "send failed" << endl; } } system("pause"); closesocket(so); WSACleanup(); return 0; }
    //server
    #include <iostream> #include <winsock2.h> #include <windows.h> #pragma comment(lib, "WS2_32") // 链接到WS2_32.lib using namespace std; int main() { //有一种非阻塞的socket,没有用过 SOCKET so; WSADATA ws; if (WSAStartup(MAKEWORD(2, 2), &ws) != 0) { cout << "WSAStartup failed" << endl; } if((so = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)//创建socket { cout << "scoket failed" << endl; } sockaddr_in addr = {0}; addr.sin_addr.s_addr = inet_addr("127.0.0.1");//将字符串ip地址转换成网络字节顺序的整型值 addr.sin_family = AF_INET; addr.sin_port = htons(2000);//此地址是网络字节序,需要将主机字节序抓换成网络字节序 //addr.sin_zero if(bind(so, (struct sockaddr*)&addr, sizeof(sockaddr)) != 0)//bind { cout << "bind failed" << endl; } if(listen(so, 10) == -1)//监听so套接字 { cout << "listen failed" << endl; } sockaddr_in addrclient; int client; int nrecv; char buff[4096]; while (true) { if((client = accept(so, (struct sockaddr*)&addrclient, NULL)) == -1)//accept客户端的连接,返回连接的套接字,此函数时阻塞函数 { continue; } //输出IP //cout << inet_ntoa(addrclient.sin_addr.s_addr);//将网络格式的ip转换成.分格式的字符串 while (true) { nrecv = recv(client, buff, 4096, 0);//recv也是阻塞函数 buff[nrecv] = ''; cout << buff << endl; } } WSACleanup(); system("pause"); return 0; }

    有点小bug

  • 相关阅读:
    客户端命令行查看dubbo服务的生产者和消费者
    灰度发布
    灰度发布方法了解
    spring事务隔离级别
    小东西
    从excel表中生成批量SQL,将数据录入到数据库中
    CSV导出
    详解Java的自动装箱与拆箱(Autoboxing and unboxing)
    java多线程理解
    spring事务传播行为讲解转载
  • 原文地址:https://www.cnblogs.com/zzyoucan/p/3804329.html
Copyright © 2020-2023  润新知