21xrx.com
2024-12-22 20:35:03 Sunday
登录
文章检索 我的文章 写文章
C++ TCP 客户端制作教程
2023-06-27 16:49:02 深夜i     --     --
C++ TCP 客户端制作 教程

C++作为一门古老但依旧广泛应用的编程语言,在网络编程方面表现出色。在本教程中,我们将探讨如何使用C++创建一个TCP客户端。

初始化Winsock库

Winsock是Windows操作系统网络编程的核心插件,需要在程序中初始化。我们可以使用以下函数:


#include <winsock2.h>

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

WSADATA wsaData;

int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);

if (iResult != 0) {

  printf("WSAStartup failed: %d\n", iResult);

  return 1;

}

之后我们将能够使用Windows Socket API。

创建TCP套接字

使用以下函数创建一个TCP套接字:


SOCKET ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

指定服务器地址和端口

我们需要知道连接的远程IP地址和端口号。我们将使用一个sockaddr_in结构体来指定服务器地址和端口。设置以下字段:


sockaddr_in clientService;

clientService.sin_family = AF_INET;

clientService.sin_addr.s_addr = inet_addr("127.0.0.1"); // 远程IP地址

clientService.sin_port = htons(27015); // 远程端口号

与服务器建立连接

通过以下代码,使用套接字尝试与服务器建立连接:


int iResult = connect(ConnectSocket, (SOCKADDR *)&clientService, sizeof(clientService));

if (iResult == SOCKET_ERROR) {

  printf("Unable to connect to server: %d\n", WSAGetLastError());

  closesocket(ConnectSocket);

  WSACleanup();

  return 1;

}

现在,我们可以与远程服务器通信,发送和接收数据。

发送和接收数据

使用以下函数发送数据:


const char *sendbuf = "this is a test";

iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);

if (iResult == SOCKET_ERROR) {

  printf("send failed: %d\n", WSAGetLastError());

  closesocket(ConnectSocket);

  WSACleanup();

  return 1;

}

使用以下函数接收数据:


char recvbuf[DEFAULT_BUFLEN];

iResult = recv(ConnectSocket, recvbuf, DEFAULT_BUFLEN, 0);

if (iResult > 0) {

  printf("Bytes received: %d\n", iResult);

  printf("Received data: %s\n", recvbuf);

} else if (iResult == 0) {

  printf("Connection closed\n");

} else {

  printf("recv failed: %d\n", WSAGetLastError());

  closesocket(ConnectSocket);

  WSACleanup();

  return 1;

}

尝试关闭连接

使用以下代码,关闭连接:


iResult = shutdown(ConnectSocket, SD_SEND);

if (iResult == SOCKET_ERROR) {

  printf("shutdown failed: %d\n", WSAGetLastError());

  closesocket(ConnectSocket);

  WSACleanup();

  return 1;

}

完整程序代码


#include <winsock2.h>

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

#include <stdio.h>

#define DEFAULT_BUFLEN 512

int main() {

  WSADATA wsaData;

  int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);

  if (iResult != 0) {

    printf("WSAStartup failed: %d\n", iResult);

    return 1;

  }

  SOCKET ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

  if (ConnectSocket == INVALID_SOCKET) {

    printf("Error at socket: %ld\n", WSAGetLastError());

    WSACleanup();

    return 1;

  }

  sockaddr_in clientService;

  clientService.sin_family = AF_INET;

  clientService.sin_addr.s_addr = inet_addr("127.0.0.1"); // 远程IP地址

  clientService.sin_port = htons(27015); // 远程端口号

  iResult = connect(ConnectSocket, (SOCKADDR *)&clientService, sizeof(clientService));

  if (iResult == SOCKET_ERROR) {

    printf("Unable to connect to server: %d\n", WSAGetLastError());

    closesocket(ConnectSocket);

    WSACleanup();

    return 1;

  }

  const char *sendbuf = "this is a test";

  iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);

  if (iResult == SOCKET_ERROR) {

    printf("send failed: %d\n", WSAGetLastError());

    closesocket(ConnectSocket);

    WSACleanup();

    return 1;

  }

  char recvbuf[DEFAULT_BUFLEN];

  iResult = recv(ConnectSocket, recvbuf, DEFAULT_BUFLEN, 0);

  if (iResult > 0) {

    printf("Bytes received: %d\n", iResult);

    printf("Received data: %s\n", recvbuf);

  } else if (iResult == 0) {

    printf("Connection closed\n");

  } else {

    printf("recv failed: %d\n", WSAGetLastError());

    closesocket(ConnectSocket);

    WSACleanup();

    return 1;

  }

  iResult = shutdown(ConnectSocket, SD_SEND);

  if (iResult == SOCKET_ERROR) {

    printf("shutdown failed: %d\n", WSAGetLastError());

    closesocket(ConnectSocket);

    WSACleanup();

    return 1;

  }

  closesocket(ConnectSocket);

  WSACleanup();

  return 0;

}

总结

在本教程中,我们学习了如何在C++中创建TCP客户端。通过了解Winsock库和Windows Socket API,我们能够创建客户端和服务器应用程序。使用本文提供的代码样例,您可以快速学习如何使用C++编写TCP客户端,并开始开发自己的网络应用程序。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复