1 Star 0 Fork 0

2144/Socket-CentOS

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
TcpSocket.h 1.54 KB
一键复制 编辑 原始数据 按行查看 历史
root 提交于 2023-07-06 01:01 . initial commit
#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);
}
};
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/iamherer/socket-cent-os.git
git@gitee.com:iamherer/socket-cent-os.git
iamherer
socket-cent-os
Socket-CentOS
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385