当前位置:网站首页>Socket programming demo II
Socket programming demo II
2022-07-04 19:34:00 【Fat Da meow who can fly】
1、 establish main.cpp
#include <stdlib.h>
#include "XTcp.h"
#include <thread>
#include <string.h>
class TcpThread {
public:
void Main() {
//windows It's not read Of
char buf[1024] = {
0 };
while (true) {
int recvlen = clientFd.Recv( buf, sizeof(buf) - 1);// fd buffer size flag
if (recvlen <= 0) {
break;
}
buf[recvlen] = '\n';
if (strstr(buf, "quit") != NULL) {
char re[] = "quit success!\n";
clientFd.Send(re, strlen(re) + 1);
printf("exit;");
break;
}
int sendlen = clientFd.Send( "ok\n", 3);
// recv/send There is no guarantee that all data will be received or sent
printf("sendlen:%d\n", sendlen);
printf("recv %s\n", buf);
}
clientFd.Close();
delete this;
}
XTcp clientFd;
};
int main(int argc, char* argv[]) {
unsigned short port = 8080;
if (argc > 1) {
port = atoi(argv[1]);// Read the command line arguments
}
XTcp server;
server.CreateSocket();
server.Bind(port);
for (;;) {
XTcp client = server.Accept();
TcpThread* th = new TcpThread;
th->clientFd = client;
std::thread sth(&TcpThread::Main, th);
sth.detach();// The main thread releases the resources of the sub threads owned by the main thread , The business logic is handed over to the child thread
}
server.Close();
//char c = getchar();
return 0;
}
2、 establish XTcp.h
#pragma once
#include <string>
class XTcp
{
public:
int CreateSocket();
bool Bind(unsigned short port);
XTcp Accept();
void Close();
int Recv(char *buf,int bufsize);
int Send(const char *buf,int bufsize);
XTcp();
virtual ~XTcp();
int socketFd = 0;
unsigned short port = 0;
std::string ip;
};
3、 establish XTcp.cpp
#include "XTcp.h"
#include<stdio.h>
#include <string.h>
#ifdef _WIN64
#include<ws2tcpip.h>
#include<Windows.h>
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#define closesocket close
#endif
#include <thread>
using namespace std;
XTcp::XTcp() {
#ifdef _WIN64
static bool first = true;
if (first) {
first = false;
WSADATA ws;
WSAStartup(MAKEWORD(2, 2), &ws);
}
#endif
}
int XTcp::CreateSocket() {
// Cause binding error
//int socketFd = socket(AF_INET, SOCK_STREAM, 0);
socketFd = socket(AF_INET, SOCK_STREAM, 0);
if (socketFd == -1) {
printf("created socket failed!\n");
return -1;
}
return socketFd;
}
bool XTcp::Bind(unsigned short port) {
if (socketFd == 0) {
CreateSocket();
}
sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_port = htons(port);// Convert local byte order to network byte order
saddr.sin_addr.s_addr = htonl(0);
int bindRes = ::bind(socketFd, (sockaddr*)&saddr, sizeof(saddr));
if (bindRes != 0) {
printf("bind port %d failed!\n", port);
return false;
}
printf("bind port %d success!\n", port);
listen(socketFd, 10);//10 Linked queues , wait for accept The maximum waiting queue for processing
return true;
}
XTcp XTcp::Accept() {
XTcp tcp;
sockaddr_in caddr;
//int len = 0;
socklen_t len = sizeof(caddr);
int clientFd = accept(socketFd, (sockaddr*)&caddr, &len);// Corresponding request client Of socketFd, Can be used to read the corresponding client The data of
if (clientFd < 0) return tcp;
printf("accept client %d\n", clientFd);
tcp.ip = inet_ntoa(caddr.sin_addr); // Convert to string
tcp.port = ntohs(caddr.sin_port);
tcp.socketFd = clientFd;
printf("client ip is %s,port is %d \n", tcp.ip.c_str(), tcp.port);
return tcp;
}
void XTcp::Close() {
if (socketFd <= 0) {
closesocket(socketFd);
}
};
int XTcp::Recv(char* buf, int bufsize) {
return recv(socketFd, buf, bufsize, 0);
}
int XTcp::Send(const char* buf, int bufsize) {
int slen = 0;
while (slen != 0) {
int len = send(socketFd, buf + slen, bufsize - slen, 0);
if (len <= 0) {
break;
}
slen += len;
}
return slen;
}
XTcp::~XTcp() {
}
4、 establish makefile file
tcpserver:main.cpp XTcp.cpp XTcp.h
g++ XTcp.cpp main.cpp -o tcpserver -std=c++11 -lpthread
5、 perform make
sudo make
6、 Start server
./tcpserver
7、 Test connection
telnet 192.168.3.15 8080
边栏推荐
- 1005 Spell It Right(20 分)(PAT甲级)
- Functional interface
- 1002. A+B for Polynomials (25)(PAT甲级)
- Shell 编程核心技术《三》
- Shell programming core technology "three"
- 2014 Hefei 31st youth informatics Olympic Games (primary school group) test questions
- Opencv functions and methods related to binary threshold processing are summarized for comparison and use
- C # implementation defines a set of SQL statements that can be executed across databases in the middle of SQL (detailed explanation of the case)
- Shell 編程核心技術《四》
- 876. Intermediate node of linked list
猜你喜欢
用实际例子详细探究OpenCV的轮廓绘制函数drawContours()
PolyFit软件介绍
There are multiple divs in the large div, which are displayed on the same line. After overflow, scroll bars are generated without line breaks
Online sql to excel (xls/xlsx) tool
Upgrade the smart switch, how much is the difference between the "zero fire version" and "single fire" wiring methods?
Mysql database basic operation -ddl | dark horse programmer
Summary and sorting of 8 pits of redis distributed lock
Some thoughts on whether the judgment point is located in the contour
One question per day (2022-07-02) - Minimum refueling times
mysql中explain语句查询sql是否走索引,extra中的几种类型整理汇总
随机推荐
如何使用Async-Awati异步任務處理代替BackgroundWorker?
PolyFit软件介绍
A method of using tree LSTM reinforcement learning for connection sequence selection
Detailed explanation of issues related to SSL certificate renewal
How test engineers "attack the city" (Part I)
1007 Maximum Subsequence Sum(25 分)(PAT甲级)
Guys, for help, I use MySQL CDC 2.2.1 (Flink 1.14.5) to write Kafka and set
Qt实现界面滑动切换效果
mysql中explain语句查询sql是否走索引,extra中的几种类型整理汇总
26. Delete the duplicate item C solution in the ordered array
Unity给自己的脚本添加类似编辑器扩展的功能案例ContextMenu的使用
The difference and usage between substr (), slice (), and substring () in the string interception methods of "understand series after reading"
1006 Sign In and Sign Out(25 分)(PAT甲级)
1009 Product of Polynomials(25 分)(PAT甲级)
LM10丨余弦波动顺势网格策略
Have you guys ever used CDC direct Mysql to Clickhouse
Go microservice (II) - detailed introduction to protobuf
Shell programming core technology "I"
. Net ORM framework hisql practice - Chapter 2 - using hisql to realize menu management (add, delete, modify and check)
One question per day (2022-07-02) - Minimum refueling times