跨平台tcp socket通信C++类

可在windows和linux上运行

//TcpClient.h

#pragma once

#include <string>

class CTcpClient
{
public:
	CTcpClient();
	virtual ~CTcpClient();

	void Close();
	bool Connect(const char *ip, unsigned short port);

	int Recv(char *buf, int bufsize);
	int Send(const char *buf, int sendsize);
	
private:
	int m_sockfd;
};

//TcpClient.cpp

#include "TcpClient.h"

#ifdef WIN32
#include <WinSock2.h>
#include <windows.h>
#define write(fd,buf,len) send((fd),(buf),(len),0)
#define read(fd,buf,len) recv((fd),(buf),(len),0)
#else
#include <sys/socket.h>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#define closesocket close
#endif


CTcpClient::CTcpClient()
{
#ifdef WIN32
	WSADATA wsaData;
	int err = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (err != 0)
	{
		printf("WSAStartup error\n");
	}
#endif
}

CTcpClient::~CTcpClient()
{
#ifdef WIN32
	WSACleanup();
#endif
}


bool CTcpClient::Connect(const char *ip, unsigned short port)
{
	struct sockaddr_in clientAddr;
	int length = 0;

	m_sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (m_sockfd == -1)
	{
		return false;
	}
	else
	{
		clientAddr.sin_family = AF_INET;
		//服务器的地址
		clientAddr.sin_addr.s_addr = inet_addr(ip);
		clientAddr.sin_port = htons(port);

		length = sizeof(clientAddr);
		if (connect(m_sockfd, (struct sockaddr*)&clientAddr, length) == -1)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
}

int CTcpClient::Recv(char* buf, int bufsize)
{
	return recv(m_sockfd, buf, bufsize, 0);
}

int CTcpClient::Send(const char* buf, int size)
{
	int s = 0;
	while (s != size)  
	{
		int len = send(m_sockfd, buf + s, size - s, 0);
		if (len <= 0)
		{
			break;
		}
		s += len;
	}
	return s;
}

void CTcpClient::Close()
{
	if (m_sockfd <= 0)
	{
		return;
	}
	closesocket(m_sockfd);
}

调用方法

CTcpClient tcpClient;
tcpClient.Connect("192.168.1.1", 12000);
tcpClient.Send("test", 5);
char receive[128] = {0};
tcpClient.Recv(receive,sizeof(receive));
printf("%s\n", receive);

后续:https://blog.csdn.net/qq_40321622/article/details/131005370?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22131005370%22%2C%22source%22%3A%22qq_40321622%22%7D

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值