代码拉取完成,页面将自动刷新
#pragma once
#include <iostream>
#include <vector>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
struct TcpSocket
{
struct Desc
{
const char *host = "127.0.0.1";
unsigned int port = 1234;
unsigned int af = AF_INET;
unsigned int type = SOCK_STREAM;
unsigned int protocol = IPPROTO_TCP;
unsigned int sinFamily = AF_INET;
};
int client_sock;
bool Create(const Desc &desc)
{
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr)); // use 0 to initialize every byte
serv_addr.sin_family = desc.sinFamily; // use IPV4
serv_addr.sin_addr.s_addr = inet_addr(desc.host); // define IP
serv_addr.sin_port = htons(desc.port); // define port
// creat socket and establish connection with server
client_sock = socket(desc.af, desc.type, desc.protocol);
int res = connect(client_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if (res != 0)
{
printf("connect failed %d\n", res);
return false;
}
printf("connect success");
return true;
};
void Close()
{
close(client_sock); // 关闭
}
template <typename T>
int Recv(T &t)
{
return recv(client_sock, (char *)&t, sizeof(T), 0);
}
template <typename T>
int Send(const T &t)
{
return send(client_sock, (const char *)&t, sizeof(T), 0);
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。