当前位置:网站首页>Socket Programming TCP
Socket Programming TCP
2022-06-12 11:22:00 【Diligent_ wu】
TCP Communication programming
TCP Communication programming process :
Simulate the process of communication between the server and the client :
Use of interfaces :
1. Create socket :
int socket(int domain,int type,int protocol)
domain: Address field AF_INET/AF_INET6
type:SOCK_STREAM(TCP Streaming socket ) SOCK_DGRAM(UDP Socket datagram )
protocol:IPPROTO_TCP IPPROTO_UDP
return socket Operation handle
2. Binding address information :
int bind(int sockfd,(struct sockaddr*)addr,socklen_t len)
3. Start listening
listen(int sockfd,int backlog)
sockfd: Which socket Set as listening socket , Just pass in the handle of which socket
backlog: Number of concurrent connections at the same time , Determine the maximum number of client connection requests accepted at the same time
If a malicious host sends unlimited connection requests to the server at the same time , Whether the server should always create sockets for each request ? If so , In the end, there is only one structure, that is, resource exhaustion , System crash .
backlog That's the solution , As mentioned in the previous process , Monitoring phase , The listening server receives a connection request to create a socket and put it into the incomplete connection queue , Bind the quintuple information and put it into the completed connection queue .
backlog This determines the number of nodes in the incomplete connection queue . But it only determines the number of nodes at the same time , But it does not determine the maximum client connection that the system can accept .
4. Get new connection
Take a... From the completed connection queue socket, Go back to this socket Operation handle of , So you can communicate .
int accept(int sockfd,(struct sockaddr*)cli_addr,socklen* len);
sockfd : Listening socket , Indicates which... To get tcp New connection of server socket ( There could be a lot TCP Server side )
cli_addr: The client address information of the new socket
len: Length of address information
Return value : New socket operation handle --- Socket handle in external program
5. Sending and receiving data
ssize_t recv(int sockfd,char* buf,int len,int flag);
Default block , No data, wait , Disconnect and return 0, It's not blocking
ssize_t send(int sockfd,char* data,int len,int flag);
Default block , When the buffer is full, wait , When the connection is disconnected, start SIGPIPE abnormal
6. Close socket
close(sockfd); #include<unistd.h>
7. Send a connection request
int connect(int sockfd,struct sockaddr* srv_addr, int len);
srv_addr: Address information of the server
connet This interface also describes the address information of the server ( Quintuples ), So you only need to send and receive data directly .
Simple and easy TCP Communication process
socket Class encapsulation
Encapsulates a TcpSocket class , Every instantiated object is a udp Communication connection , Complete the communication process through the member methods of this object .
class TcpSocket{
public:
TcpSocket():_sockfd(-1);
bool Socket();
bool Bind(const std::string& ip,uint16_t port);
bool Listen(int backlog = MAX_LISTEN);
bool Accept(TcpSocket* new_sock,std::string* ip =NULL,uint16_t* port);
bool recv(std::string* buf);
bool send(const std::string& data);
bool Close();
bool Connect(const std::string& ip,uint16_t port);
private:
int _sockfd;
#pragma once
#include<iostream>
#include<string>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
using namespace std;
class TcpSocket
{
private:
int sockfd;
public:
TcpSocket()
{
if(!Socket())
{
cout<<"socket create failed"<<endl;
}
}
~TcpSocket()
{
Close();
}
public:
bool Socket()
{
sockfd = socket(AF_INET,SOCK_STREAM,0);
if(sockfd == 0)
{
cerr<<"scoket error"<<endl;
return false;
}
return true;
}
// May be wrong
void Addr(struct sockaddr_in* addr, const string& ip,const uint16_t& port)
{
addr->sin_family = AF_INET;
addr->sin_port = htons(port);
addr->sin_addr.s_addr = inet_addr(ip.c_str());
}
bool Bind(const string& ip,const uint16_t& port)
{
struct sockaddr_in addr;
Addr(&addr,ip,port);
socklen_t len = sizeof(addr);
int ret = bind(sockfd,(struct sockaddr*)&addr,len);
if(ret < 0)
{
cerr<<"bind errror"<<endl;
return false;
}
return true;
}
bool Listen()
{
int ret = listen(sockfd,5);
if(ret == -1)
{
cerr<<"listen error"<<endl;
return false;
}
return true;
}
bool Connect(const string& ip,const uint16_t& port)
{
struct sockaddr_in addr;
Addr(&addr,ip,port);
socklen_t len = sizeof(addr);
int ret = connect(sockfd,(struct sockaddr*)&addr,len);
if(ret < 0)
{
cerr<<"connect error"<<endl;
return false;
}
return true;
}
bool Accept(TcpSocket* new_sock,string* ip = NULL,uint16_t* port = NULL)
{
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
int newfd = accept(sockfd,(struct sockaddr*)&addr,&len);
if(newfd < 0)
{
cerr<<"accept error"<<endl;
return false;
}
new_sock->sockfd = newfd;
if(ip != NULL)
{
*ip = inet_ntoa(addr.sin_addr);
}
if(port != NULL)
{
*port = ntohs(addr.sin_port);
}
return true;
}
bool Recv(string* buf)
{
char tmp[4096] = {
0};
int ret = recv(sockfd,tmp,4095,0);;
if(ret <0)
{
cerr<<"recv error"<<endl;
return false;
}
*buf = tmp;
buf->assign(tmp);
return true;
}
bool Send(const string& data)
{
//UDP Is datagram transmission , The whole delivery
// and TCP It's byte streaming , Transmit as much as you can , Data boundaries are not distinguished
// If the other side's buffer is left 50 Bytes of space ,send Give each other 100 Bytes , Can only be successfully sent 50 Bytes , And return the transfer size 50 byte
size_t total = 0 ;
while(total < data.size())
{
int ret = send(sockfd,&data[0]+total,data.size()-total,0);
if(ret < 0)
{
cerr<<"send error"<<endl;
return false;
}
total+=ret;
}
return true;
}
bool Close()
{
close(sockfd);
return true;
}
};
边栏推荐
- Distributed storage exploration
- k59.第二章 基于二进制包安装kubernetes v1.23 --集群部署
- Differences among various cross compiling tools of arm
- Drqueueonrails integrated LDAP authentication
- 命名规范/注释规范/逻辑规范
- Common port description
- AcWing 41. Stack containing min function (monotone stack)
- Mcuxpresso develops NXP rt1060 (3) -- porting lvgl to NXP rt1060
- K59. Chapter 2 installing kubernetes V1.23 based on binary packages -- cluster deployment
- Malicious code analysis practice - lab06-01 exe~Lab06-04. Exe dynamic analysis
猜你喜欢

Distributed storage exploration

21 reasons why you need social media QR code

【clickhouse专栏】基础数据类型说明

Signal relay rxsf1-rk271018dc110v

记录一下使用JPA时遇到的坑

M-Arch(番外11)GD32L233评测-PWM驱动有源蜂鸣器

^33 variable promotion and function promotion interview questions

你需要社交媒体二维码的21个理由

AcWing 128. Editor (to effectively modify the specified position in the top stack)

分布式存储探索
随机推荐
FPGA开发——Hello_world例程
SOT23(Small Outline Transistor)
AcWing 131. 直方图中最大的矩形(单调栈经典运用 模板)
Reading mysql45 lecture - self summary (part)
The reason why scanf return value is ignored and its solution
rosbridge使用案例心得总结之_第26篇在同一个服务器上打开多个rosbridge服务监听端口
元宇宙系统搭建与构造
2022-06-11: note that in this document, graph is not the meaning of adjacency matrix, but a bipartite graph. In the adjacency matrix with length N, there are n points, matrix[i][j]
Epidemic home office experience | community essay solicitation
Clickhouse column basic data type description
AI - face
B+ 树的简单认识
The most detailed explanation of the top ten levels of sqli labs platform
Zabbix 监控之LLD
Golang基础(6)
LVS基于应用层的健康状态检测
Signal relay rxsf1-rk271018dc110v
InfoQ geek media's 15th anniversary solicitation |position:fixed virtual button cannot take effect after being triggered. Problem analysis and Solution Exploration
CLJ3-100ALH30剩余电流继电器
人脸识别pip 安装dlib库失败