前言:不会实现C/S互相发送数据进行Socket通信的朋友,可见博客C++实现Windows下服务端与客户端Socket通信(一)
一.本文主要介绍用Socket传输不同类型的数据四种方式
①结构体
②类对象
③Protobuf
④Json
1.1 使用结构体
I.假设需要传输的结构体数据如下:
注意:(发送方和接收方都需要定义相同的结构体)
struct Student
{
int iId;
string strName;
bool bSex; //为了节省内存空间,性别采用一个字节的BOOL类型表示
};
II.发送方代码(客户端)
struct Student stu; //声明一个Student结构体变量
stu.iId = 1001;
stu.bSex = true; //true表示男性,false表示女性,你反过来也行,别打拳
stu.strName = "abcdefzzzzz";
//下面的m_sclient是客户端(发送方)的Socket套接字
//方法一:推荐如下
send(m_sclient, (char*)&stu, sizeof(Student), 0);//&stu取stu地址,(char*)转化为char类型的指针
//方法二:或者增加一个中间变量sendBuff[]来传送,如下
//char sendBuff[1024];
//memset(sendBuff,0,sizeof(sendBuff));
//memcpy(sendBuff, &stu, sizeof(Student));
//send(m_sclient, sendBuff, sizeof(sendBuff), 0);
III.接收方代码(服务端)
struct Student stu; //声明一个结构体变量,用于接收客户端(发送方)发来的数据
char buffFromClient[1024]; //用于临时接收发送方的数据
//方法一:(推荐)
recv(clientSocket, (char*)&stu, sizeof(Student), 0);
//方法二:
//memset(buffFromClient,0,sizeof(buffFromClient));
//recv(clientSocket, buffFromClient, sizeof(Student), 0);
//memset(&stu,buffFromClent,sizeof(Student));
1.2 使用类对象
I.添加StudentInfo类
注意:(发送方和接收方都需要定义相同结构的类对象)
//StudentInfo.h文件如下,.cpp文件自行实现
#pragma once
#include <iostream>
using namespace std;
class StudentInfo
{
private:
int m_iId;
string m_strName;
bool m_bSex;
public:
StudentInfo();
~StudentInfo();
int GetId();
string GetName();
bool GetSex();
void SetId(int iId);
void SetName(string strName);
void SetSex(bool bSex);
};
II.发送方代码(客户端)
初始化类对象并发送数据
//初始化stuInfo类对象
StudentInfo stuInfo;
stuInfo.SetId(111);
stuInfo.SetName("abcdefzzzzz");
stuInfo.SetSex(true);
send(m_clientSocket, (char*)&stuInfo, sizeof(StudentInfo), 0);
II.接收方代码(服务端)
定义类对象并接收数据
StudentInfo stuInfo;
int iLenOfRecvData = -1;
//传输类对象数据
iLenOfRecvData = recv(clientSocket, (char*)&stuInfo, sizeof(StudentInfo), 0);
if (iLenOfRecvData > 0) //如果接收的数据不为空
{
cout << stuInfo.GetId() << endl;
cout << stuInfo.GetName() << endl;
cout << stuInfo.GetSex() << endl;
}
以上内容更新于2022.4.6
未完待续...