当前位置:网站首页>socket编程demo二
socket编程demo二
2022-07-04 18:01:00 【会飞的胖达喵】
1、创建main.cpp
#include <stdlib.h>
#include "XTcp.h"
#include <thread>
#include <string.h>
class TcpThread {
public:
void Main() {
//windows 是没有read的
char buf[1024] = {
0 };
while (true) {
int recvlen = clientFd.Recv( buf, sizeof(buf) - 1);// fd buffer 大小 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都不能保证一定能接受或者发送完所有的数据
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]);//读取命令行参数
}
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();//主线程释放主线程拥有的子线程的资源释放掉,业务逻辑交给子线程
}
server.Close();
//char c = getchar();
return 0;
}
2、创建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、创建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() {
// 导致绑定错误
//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);//本地字节序转成网络字节序
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个链接的队列,等待accept处理的队列最大等待队列
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);// 对应请求client的socketFd,可以用来读取对应client的数据
if (clientFd < 0) return tcp;
printf("accept client %d\n", clientFd);
tcp.ip = inet_ntoa(caddr.sin_addr); //转成字符串
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、创建makefile文件
tcpserver:main.cpp XTcp.cpp XTcp.h
g++ XTcp.cpp main.cpp -o tcpserver -std=c++11 -lpthread
5、执行make
sudo make
6、启动服务端
./tcpserver
7、测试连接
telnet 192.168.3.15 8080
边栏推荐
- 1011 World Cup Betting (20 分)(PAT甲级)
- 1008 Elevator(20 分)(PAT甲级)
- 2019年蜀山区第十五届青少年信息学竞赛
- redis分布式锁的8大坑总结梳理
- To sort out messy header files, I use include what you use
- 876. Intermediate node of linked list
- Oracle with as ORA-00903: invalid table name 多表报错
- 问下各位大佬有用过cdc直接mysql to clickhouse的么
- LeetCode FizzBuzz C#解答
- 项目中遇到的线上数据迁移方案1---总体思路整理和技术梳理
猜你喜欢
English语法_名词 - 使用
There are multiple divs in the large div, which are displayed on the same line. After overflow, scroll bars are generated without line breaks
与二值化阈值处理相关的OpenCV函数、方法汇总,便于对比和拿来使用
Use canal and rocketmq to listen to MySQL binlog logs
整理混乱的头文件,我用include what you use
线上数据库迁移的几种方法
mysql中explain语句查询sql是否走索引,extra中的几种类型整理汇总
一文掌握数仓中auto analyze的使用
The latest progress of Intel Integrated Optoelectronics Research promotes the progress of CO packaging optics and optical interconnection technology
A method of using tree LSTM reinforcement learning for connection sequence selection
随机推荐
To sort out messy header files, I use include what you use
性能优化之关键渲染路径
C#实现定义一套中间SQL可以跨库执行的SQL语句(案例详解)
An example of multi module collaboration based on NCF
C # implementation defines a set of SQL statements that can be executed across databases in the middle of SQL (detailed explanation of the case)
[release] a tool for testing WebService and database connection - dbtest v1.0
Shell 编程核心技术《一》
数组中的第K个最大元素
自由小兵儿
升级智能开关,“零火版”、“单火”接线方式差异有多大?
Online text line fixed length fill tool
The 15th youth informatics competition in Shushan District in 2019
Caché WebSocket
Don't just learn Oracle and MySQL!
26. Delete the duplicate item C solution in the ordered array
2022CoCa: Contrastive Captioners are Image-Text Fountion Models
FPGA timing constraint sharing 01_ Brief description of the four steps
2019年蜀山区第十五届青少年信息学竞赛
Unity编辑器扩展C#遍历文件夹以及子目录下的所有图片
Explore the contour drawing function drawcontours() of OpenCV in detail with practical examples