首页 > 编程语言 >C++实现简单的tcp协议

C++实现简单的tcp协议

时间:2024-09-29 19:49:24浏览次数:8  
标签:std 协议 const iResult int C++ cerr tcp include

Server.cpp

#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>

#pragma comment(lib, "ws2_32.lib")

const int PORT = 8888;
const int BUFFER_SIZE = 1024;

int main() {
    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        std::cerr << "WSAStartup failed: " << iResult << std::endl;
        return 1;
    }

    SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket == INVALID_SOCKET) {
        std::cerr << "socket failed: " << WSAGetLastError() << std::endl;
        WSACleanup();
        return 1;
    }

    sockaddr_in serverAddress;
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_addr.s_addr = INADDR_ANY;
    serverAddress.sin_port = htons(PORT);

    if (bind(serverSocket, reinterpret_cast<sockaddr*>(&serverAddress), sizeof(serverAddress)) == SOCKET_ERROR) {
        std::cerr << "bind failed: " << WSAGetLastError() << std::endl;
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }

    if (listen(serverSocket, SOMAXCONN) == SOCKET_ERROR) {
        std::cerr << "listen failed: " << WSAGetLastError() << std::endl;
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }

    std::cout << "Server listening on port " << PORT << std::endl;

    sockaddr_in clientAddress;
    int clientAddressSize = sizeof(clientAddress);
    SOCKET clientSocket = accept(serverSocket, reinterpret_cast<sockaddr*>(&clientAddress), &clientAddressSize);
    if (clientSocket == INVALID_SOCKET) {
        std::cerr << "accept failed: " << WSAGetLastError() << std::endl;
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }

    char buffer[BUFFER_SIZE];
    int bytesRead;
    while ((bytesRead = recv(clientSocket, buffer, BUFFER_SIZE, 0)) > 0) {
        buffer[bytesRead] = '\0';
        std::cout << "Received from client: " << buffer << std::endl;
        send(clientSocket, buffer, bytesRead, 0);
    }

    if (bytesRead == SOCKET_ERROR) {
        std::cerr << "recv failed: " << WSAGetLastError() << std::endl;
    }

    closesocket(clientSocket);
    closesocket(serverSocket);
    WSACleanup();
    system("pause");
    return 0;
}

 Client.cpp

#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>

#pragma comment(lib, "ws2_32.lib")

const int PORT = 8888;
const int BUFFER_SIZE = 1024;

int main() {
    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        std::cerr << "WSAStartup failed: " << iResult << std::endl;
        return 1;
    }

    SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (clientSocket == INVALID_SOCKET) {
        std::cerr << "socket creation failed: " << WSAGetLastError() << std::endl;
        WSACleanup();
        return 1;
    }

    sockaddr_in serverAddress;
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_port = htons(PORT);
    inet_pton(AF_INET, "127.0.0.1", &serverAddress.sin_addr.s_addr);

    if (connect(clientSocket, reinterpret_cast<sockaddr*>(&serverAddress), sizeof(serverAddress)) == SOCKET_ERROR) {
        std::cerr << "connect failed: " << WSAGetLastError() << std::endl;
        closesocket(clientSocket);
        WSACleanup();
        return 1;
    }

    std::cout << "Connected to server." << std::endl;

    char message[] = "Hello from client!";
    send(clientSocket, message, strlen(message), 0);

    char buffer[BUFFER_SIZE];
    int bytesRead = recv(clientSocket, buffer, BUFFER_SIZE, 0);
    if (bytesRead > 0) {
        buffer[bytesRead] = '\0';
        std::cout << "Received from server: " << buffer << std::endl;
    }
    else {
        std::cerr << "recv failed: " << WSAGetLastError() << std::endl;
    }

    closesocket(clientSocket);
    WSACleanup();
    system("pause");
    return 0;
}

使用环境

大家可在vs中在同一解决方案下建立两个项目,先运行Server.cpp再运行Client.cpp即可。

有问题留言!

标签:std,协议,const,iResult,int,C++,cerr,tcp,include
From: https://blog.csdn.net/2301_80165072/article/details/142619455

相关文章

  • Python和C++及MATLAB距离相关性生物医学样本统计量算法及数据科学
    ......
  • 南沙C++信奥赛陈老师解一本通题 1942:【08NOIP普及组】ISBN号码
    ​ 【题目描述】每一本正式出版的图书都有一个ISBN号码与之对应,ISBN码包括9位数字、1位识别码和3位分隔符,其规定格式如“x-xxx-xxxxx-x”,其中符号“-”是分隔符(键盘上的减号),最后一位是识别码,例如0-670-82162-4就是一个标准的ISBN码。ISBN码的首位数字表示书籍的出版语音,例如......
  • C++学习:stack queue模拟
    stack和queue可以复用其他容器的函数如dequevector这两个是空间适配器,所以都没有迭代器一:stack模拟namespacebit{ template<classT,classContainer=deque<T>> classstack { public: voidpush(constT&x) { _con.push_back(x); } voidpop() ......
  • C++学习:模版进阶:非类型模板参数 特化 分离编译
    目录一:非类型模版参数二:模版特化三:函数模版特化四:类模版特化一:全特化(将模板参数列表中所有的参数都确定化)二:偏特化(部分特化或更进一步限制)五:模版分离编译一:非类型模版参数非类型模版参数是在模版参数列表中,跟在模版参数后面的,就是用常量当参数(下面的n就是)templa......
  • c++线程--快速上手
    线程创建头文件#includethread是在C++11标准中引入的。C++11标准引入了对多线程编程的标准化支持,其中包括了线程的创建、管理和同步机制。头文件提供了基本的线程支持库,允许开发者直接使用c++线程进行并行编程,而无需依赖操作系统特定的API#include<iostream>#include......
  • 基于C++11的数据库连接池环境配置
    欢迎访问我的另一个博客:https://xingzhu.top/ubuntu安装python2由于接下来要使用python,所以先安装python#安装python2.7.18即可#python3不行,版本过高,会报错sudoaptinstallpython2python2--version安装完成后我们可以使用如下命令来检查目前可用的Pyt......
  • C++的并发编程历史
    多线程环境并非所有的语言都提供了多线程的环境。即便是C++语言,直到C++11标准之前,也是没有多线程支持的。在这种情况下,Linux/Unix平台下的开发者通常会使用POSIXThreads,Windows上的开发者也会有相应的接口。但很明显,这些API都只针对特定的操作系统平台,可移植性较差。如果要同......
  • 南沙C++信奥赛陈老师解一本通题 1973:【16NOIP普及组】买铅笔
    ​ 【题目描述】P老师需要去商店买n支铅笔作为小朋友们参加NOIP的礼物。她发现商店一共有3种包装的铅笔,不同包装内的铅笔数量有可能不同,价格也有可能不同。为了公平起见,P老师决定只买同一种包装的铅笔。商店不允许将铅笔的包装拆开,因此P老师可能需要购买超过n支铅笔才够给小......
  • C# Modbus Tcp 实现(二)
    CSocketClientinfo;ModbusMastermaster;//publicstaticModbusTcp2Instance=newModbusTcp2("192.168.0.8",8000);publicstaticModbusTcp2Instance=newModbusTcp2("127.0.0.1",8000);public......
  • C# Modbus Tcp实现(一)
     类CSocketClient主要包括以下内容:privateTcpClient_client;publicThread_connectionThread;privateStreamWriter_write;publicClientRecMsgClassGClientRecMsgClass1=newClientRecMsgClass();privatestringhostn......