21xrx.com
2025-03-28 16:54:25 Friday
文章检索 我的文章 写文章
C++实现TCP通讯
2023-07-04 19:06:44 深夜i     16     0
C++ TCP 通讯 实现 网络编程

C++ 是一种高效的编程语言,它具有较高的性能和强大的功能,因此在各种应用领域都得到了广泛的应用。TCP/IP 协议是互联网通信的基础,而 C++ 在 TCP/IP 网络通讯方面也具有很强的支持能力,可以轻松实现 TCP 通讯。

首先,需要了解 TCP 协议的基本概念,TCP 是一种面向连接的协议,它通过三次握手建立连接,一旦连接建立成功,就可以进行双向数据传输。在 C++ 中,可以使用 socket 编程来实现 TCP 通讯。通过 socket 函数创建套接字,使用 bind 绑定端口,然后使用 listen 函数监听客户端连接请求,最后使用 accept 函数接受客户端连接。

下面是一个简单的 C++ TCP 通讯示例代码:

#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
int main(int argc, char* argv[])
{
  int listenfd;
  int connfd;
  struct sockaddr_in servaddr, clientaddr;
  socklen_t clilen;
  char buf[1024];
  listenfd = socket(AF_INET, SOCK_STREAM, 0);
  memset(&servaddr, 0, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(8888);
  bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
  listen(listenfd, 10);
  cout << "Server start!" << endl;
  while (true) {
    clilen = sizeof(clientaddr);
    connfd = accept(listenfd, (struct sockaddr*)&clientaddr, &clilen);
    while (true) {
      memset(buf, 0, sizeof(buf));
      int n = read(connfd, buf, sizeof(buf));
      if (n < 0) {
        perror("Read error");
        break;
      }
      if (n == 0)
        cout << "Client close the connection" << endl;
        break;
      
      cout << "Client say: " << buf << endl;
      write(connfd, buf, strlen(buf));
    }
    close(connfd);
  }
  return 0;
}

在这个示例代码中,使用 socket 函数创建了一个 TCP 套接字,然后使用 bind 函数将套接字绑定到本地IP地址和端口上。使用 listen 函数监听客户端连接请求。在主循环中,使用 accept 函数接受客户端连接请求,通过 read 函数接收客户端发送的数据,然后通过 write 函数将数据发送回客户端。当客户端关闭连接时,退出子循环。最后释放资源。

总之,使用 C++ 实现 TCP 通讯是一项非常重要的任务,它可以在各种应用领域中发挥作用,而实现 TCP 通讯的关键在于使用 socket 编程。通过 socket 函数创建套接字,使用 bind 绑定端口,使用 listen 函数监听客户端请求,使用 accept 函数接受客户端连接,然后通过 read 和 write 函数进行数据的接收和发送。

  
  

评论区