TCP通信

时间:2022-11-07 16:05:52
//网络套接字编程实例,服务器端,TCP通信。
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
    WSADATA wsaData;
    WSAStartup(MAKEWORD(,),&wsaData);  //初始化版本
    SOCKET sList = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);  //初始化socket
    if (sList == INVALID_SOCKET) //判断socket是否建立成功
    {
        cout << "socket error\n";
    }
    else
    {
        cout << "socket success\n";
    }
    sockaddr_in asd;   //申明bind中addr参数,这是申明,一个结构体。
    asd.sin_family = AF_INET;        //设置结构体,必须是:AF_INET
    asd.sin_port = htons();      //指定TCP或UDP通信服务端口号,htons函数将主机无符号短整型转换成网络字节顺序,1990是本地监听的端口号。
    asd.sin_addr.S_un.S_addr = INADDR_ANY; //INADDR_ANY表示所有可用地址
    if (bind(sList, (LPSOCKADDR)&asd, sizeof(asd)) == SOCKET_ERROR) //绑定本地IP和端口
    {
        cout << "bind error";
        closesocket(sList);
        ;
    }
    ) == SOCKET_ERROR)
    {
        cout << "listen error";
        closesocket(sList);
        ;
    }//监听,5为连接最数,注意listen只支持上面的SOCK_STREAM也就是TCP,UDP不用条用此函数。

    // 循环接受客户的连接请求
    sockaddr_in remoteAddr;
    SOCKET sClient;
    int nAddrlen = sizeof(remoteAddr);
    ];
    )
    {
        // 接受一个新连接
        sClient = accept(sList, (SOCKADDR*)&remoteAddr, &nAddrlen);
        //错误
        if (sClient == INVALID_SOCKET)
        {
            cout << "accept error";
            continue;
        }
        //打印出连接者的ip
        cout << " 接受到一个连接:" << inet_ntoa(remoteAddr.sin_addr)<<"\n";
        , );
        )
        {
            //为了防止打印出错,把字符串结尾设成0x00
            revData[ret] = 0x00;
            cout<<revData;
        }
        //发送给客户端数据
        char *buff = "握手,我是来自服务端的信息,TCP建立成功\n";
        send(sClient, buff, strlen(buff), );
        closesocket(sClient);
    }
    closesocket(sList);
    system("pause");
    ;
}
//网络套接字编程实例,客户端。
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
#include <iostream>
#include <windows.h>
#include <WS2tcpip.h>
using namespace std;

int main()
{
    WSADATA wsaData;
    WSAStartup(MAKEWORD(, ), &wsaData);  //初始化版本
    SOCKET sList = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);  //初始化socket
    if (sList == INVALID_SOCKET) //判断socket是否建立成功
    {
        cout << "socket error\n";
    }
    else
    {
        cout << "socket success\n";
    }
    sockaddr_in asd;   //申明bind中addr参数,这是申明,一个结构体。
    asd.sin_family = AF_INET;        //设置结构体,必须是:AF_INET
    asd.sin_port = htons();      //指定TCP或UDP通信服务端口号,htons函数将主机无符号短整型转换成网络字节顺序,1990是本地监听的端口号。
    asd.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //INADDR_ANY表示所有可用地址
    if (connect(sList, (sockaddr*)&asd, sizeof(asd)) == SOCKET_ERROR)
    {
        cout<<"connect error\n";
        closesocket(sList);
        ;
    }
    char *buff = "我是来自客户端的信息";
    int nAddrlen = sizeof(asd);
    ];
    send(sList, buff, strlen(buff), );
    , );
    )
    {
        revData[ret] = 0x00;
        cout << revData;
    }
    closesocket(sList);
    WSACleanup();
    system("pause");
    ;
}