首先为什么要实行分块传输字符串,一般而言Socket
套接字最长发送的字节数为8192
字节,如果发送的字节超出了此范围则后续部分会被自动截断,此时将字符串进行分块传输将显得格外重要,分块传输的关键在于封装实现一个字符串切割函数,将特定缓冲区内的字串动态切割成一个个小的子块,当切割结束后会得到该数据块的个数,此时通过套接字将个数发送至服务端此时服务端在依次循环接收数据包直到接收完所有数据包之后在组合并显示即可。
14.3.1 服务端实现
对于服务端而言只需要做两步,首先等待客户端上线,当客户端上线后则服务端会通过recv()
接收当前客户端内有多少数据包,当获取到该数据包数量后再以此数量作为循环条件,循环接收数据包并在接收后通过strcat
将数据包进行连接,最终合并为一个缓冲区,并输出即可;
#include <WinSock2.h> #include <Windows.h> #include <iostream>
#pragma comment(lib,"ws2_32.lib")
int main(int argc, char* argv[]) { WSADATA WSAData; SOCKET sock, msgsock; struct sockaddr_in ServerAddr;
if (WSAStartup(MAKEWORD(2, 0), &WSAData) != SOCKET_ERROR) { ServerAddr.sin_family = AF_INET; ServerAddr.sin_port = htons(9999); ServerAddr.sin_addr.s_addr = INADDR_ANY;
sock = socket(AF_INET, SOCK_STREAM, 0); bind(sock, (LPSOCKADDR)&ServerAddr, sizeof(ServerAddr)); listen(sock, 10); }
msgsock = accept(sock, (LPSOCKADDR)0, (int*)0);
char recv_count[1024] = { 0 }; recv(msgsock, recv_count, 1024, 0); std::cout << "收包次数: " << recv_count << std::endl; char szBuffer[8192] = { 0 };
for (int x = 0; x < atoi(recv_count); x++) { char Split[128] = { 0 }; recv(msgsock, Split, 100, 0);
strcat(szBuffer, Split); }
std::cout << "完整数据包: " << szBuffer << std::endl; closesocket(msgsock); closesocket(sock); WSACleanup(); return 0; }
|
14.3.2 客户端实现
我们将一段长字符串进行切割每次发送100个字符,该功能的实现首先依赖于Cat
函数,该函数通过传入待切割字符串指针,切割偏移以及长度,即可实现分割字符串,如下代码中通过调用Cat(szBuffer, x, 99)
切割字符串,这里我们每次剪切100个字符,并将剪切后的字符依次存储到Split[y]
这个缓冲区内,接着通过调用strlen()
依次计算出当前有多少个100字符行,并在计算结束后首先向服务端发送数据包的数量,当服务端接收到数量后会进入等待模式,此时客户端只需要通过循环的方式发送数据包即可,当然此段代码也存在问题,没有对数据包进行严格的验证,此处读者可自行完善;
#include <WinSock2.h> #include <Windows.h> #include <iostream>
#pragma comment(lib,"ws2_32.lib")
char* Cut(char* buffer, int offset, int length) { char Split[100] = { 0 };
memset(Split, 0, 100); strncpy(Split, buffer + offset, length); return Split; }
int main(int argc, char* argv[]) { WSADATA WSAData; SOCKET sock; struct sockaddr_in ClientAddr;
if (WSAStartup(MAKEWORD(2, 0), &WSAData) != SOCKET_ERROR) { ClientAddr.sin_family = AF_INET; ClientAddr.sin_port = htons(9999); ClientAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
sock = socket(AF_INET, SOCK_STREAM, 0); int Ret = connect(sock, (LPSOCKADDR)&ClientAddr, sizeof(ClientAddr)); if (Ret == 0) { char szBuffer[8192] = "hello lyshark hello lyshark hello lyshark "; char Split[100][1024] = { 0 };
for (int x = 0, y = 0; x < strlen(szBuffer); x += 99) { char* ref = Cut(szBuffer, x, 99); strcpy(Split[y], ref); y += 1; }
int rows = sizeof(Split) / sizeof(Split[0]); int count = 0; for (int x = 0; x < rows; x++) { if (strlen(Split[x]) != 0) { count += 1; } }
std::cout << "发包次数: " << count << std::endl; char send_count[1024] = { 0 }; sprintf(send_count, "%d", count); send(sock, send_count, strlen(send_count), 0);
for (int x = 0; x < count; x++) { std::cout << "发送数据包: " << Split[x] << std::endl; send(sock, Split[x], strlen(Split[x]), 0); } } } closesocket(sock); WSACleanup(); Sleep(5000); return 0; }
|
运行上述程序片段,读者可看到如下图所示的输出效果,此处只需要分割8个数据包即可完成数据的发送;