c++ 简单socket编程

1.使用多线程对每个连接进行处理
2.使用成员函数指针对消息的内容进行处理

server.cpp

#include
#include

#include
#include
#include
#include

#include
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#include
#include"handle_request.h"

#define bufferLength 1024
#define PORT  3333

int startServer(u_short *port)
{
	
	int httpd =socket(AF_INET,SOCK_STREAM,0);
	if(httpd ==-1)
	{
		printf("create socket  error");
		
	}
	struct sockaddr_in hostName;
	memset(&hostName,sizeof(hostName),0);
	
	hostName.sin_family=AF_INET;
	hostName.sin_port=htons(*port);
	hostName.sin_addr.s_addr=inet_addr("0.0.0.0");
	
	if(bind(httpd,(struct sockaddr *) &hostName,sizeof(hostName))<0)
	{
		printf("bind  error");
	}
	
	if(listen(httpd,10)<0)
	{
		printf("listen error");
	}
	
	return httpd;
}


void accept_func( void *arg)
{
	int client_sock=(intptr_t)arg;
	char str[bufferLength]={0};
	read(client_sock,str,sizeof(str));
	printf("str = %s\n",str);
	
	std::shared_ptr func =std::make_shared();
	func->RecvProFunc(str);
	
	
	
	char sendBuffer[128];
	sprintf(sendBuffer,"bye -bye  client");
	send(client_sock,sendBuffer,strlen(sendBuffer),0);
	
	close(client_sock);
	
	
	
	
}


int main()
{
	
	
	u_short  port =PORT;
	int server_sock=startServer(&port);
	printf("server listen on port %d\n",port);
	
	
	int client_sock =-1;
	struct sockaddr_in clientName;
	socklen_t  clientName_len =sizeof(clientName);
	
	while(1)
	{
		
		client_sock=accept(server_sock,(struct sockaddr *)&client_sock,&clientName_len);
		if(client_sock ==-1)
		{
			printf("client socket error");
			
		}
		
		
		std::thread([&]() {
			accept_func((void *)(intptr_t)client_sock);
			
		}).detach();
	}
	
	
	
	
}

handle_request.cpp

#include
#include"handle_request.h"
#include"rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include

typedef void  (socket_handrequest::*handle) (std::string str);

socket_handrequest::socket_handrequest()
{
	
}

socket_handrequest::~socket_handrequest()
{
	
}


void socket_handrequest::func_1(std::string str)
{
	std::cout<<"func_1:"<*statusHandler[type])(str);
	
	
	
}

你可能感兴趣的:(C++,c++网络编程)