利用boost:asio写的简单聊天服务器三

原创 2013年12月05日 14:46:50

一、服务器端源代码

5. Server.cpp  (侦听端口,接收连接,创建新CCnection)

#include "Server.h"
#include "ConnectionManager.h"
#include <boost/bind.hpp>
#include <iostream>

using namespace std;

CServer * CServer::sm_instance=NULL;

CServer * CServer::Instance()
{
    if(sm_instance==NULL)
        sm_instance=new CServer;
    return sm_instance;
}

CServer::CServer()
	: m_acceptor(CIoServiceManager::Instance()->GetIoService())
	, m_timer(CIoServiceManager::Instance()->GetIoService())
{
}

void CServer::Start(unsigned port)
{
	cout<<"CServer::Start port="<<port<<endl;
	//boost::asio::ip::tcp::resolver resolver(m_acceptor.io_service());
	//boost::asio::ip::tcp::resolver::query query(address, port);
	//boost::asio::ip::tcp::endpoint endp = *resolver.resolve(query);
	boost::asio::ip::tcp::endpoint endp(boost::asio::ip::tcp::v4(), port);
	m_acceptor.open(endp.protocol());
	m_acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
	m_acceptor.bind(endp);
	m_acceptor.listen();
	Connection_ptr  newConnection(new CConnection(CIoServiceManager::Instance()->GetIoService()));
	m_acceptor.async_accept(newConnection->Socket(),
		boost::bind(&CServer::handleAccept, this, newConnection, boost::asio::placeholders::error));
		
	m_timer.expires_from_now(boost::posix_time::seconds(15));
	m_timer.async_wait(boost::bind(&CServer::doHeartBeat, this));
}

void CServer::Stop()
{
	CIoServiceManager::Instance()->Stop();
}

void CServer::handleAccept(Connection_ptr pConn, const boost::system::error_code& er)
{
	cout<<"CServer::handleAccept()"<<endl;
	if (!er)
	{
		pConn->Start();
		Connection_ptr newConnection (new CConnection(CIoServiceManager::Instance()->GetIoService()));
		m_acceptor.async_accept(newConnection->Socket(),
			boost::bind(&CServer::handleAccept, this, newConnection, boost::asio::placeholders::error));
	}
	else
	{
		std::cout << "handleAccept Error: " << er.message() << "\n";
	}
}

void CServer::doHeartBeat()
{
	//cout<<"CServer::doHeartBeat()"<<endl;
	std::map<std::string,Connection_ptr> mapConns = CConnetionManager::Instance()->GetConnectionsMap();
	std::map<std::string,Connection_ptr>::iterator iter = mapConns.begin();
	for(; iter!=mapConns.end(); ++iter)
	{
		boost::asio::async_write(iter->second->Socket(), boost::asio::buffer("test"),
			boost::bind(&CServer::handleHeartBeat, this, boost::asio::placeholders::error, iter->first));
	}
	m_timer.expires_from_now(boost::posix_time::seconds(15));
	m_timer.async_wait(boost::bind(&CServer::doHeartBeat, this));
}

void CServer::handleHeartBeat(const boost::system::error_code& er, const string& userName)
{	
	//cout<<"CServer::handleHeartBeat()"<<endl;
	if(er)
	{
		std::cout << "handleHeartBeat Error: " << er.message() << "\n";
		CConnetionManager::Instance()->DelConnection(userName);
	}
}
6. RequestHandler.cpp (对消息内容处理)

#include "RequestHandler.h"
#include <iostream>

using namespace std;


MSG_TYPE CRequestHandler::ParseMsg(const char* data, int size)
{
	cout<<"CRequestHandler::ParseMsg()"<<endl;
	int i = 0;
	for(; i<size; i++)
	{
		if(' '==data[i])
			break;
	}
	string str(data, 0, i);
	if(str.substr(0,3)=="to:" || str.substr(0,3)=="TO:" || str.substr(0,3)=="To:")
	{
		return Send_Msg;
	}
	else if(str.substr(0,5)=="User:" || str.substr(0,5)=="user:" || str.substr(0,5)=="USER:")
	{
		return Register_Msg;
	}
	else
	{
		return Wrong_Msg;
	}
}

string CRequestHandler::GetRegisterName(const char* data, int size)
{
	cout<<"CRequestHandler::GetRegisterName()"<<endl;
	int i = 0;
	for(; i<size; i++)
	{
		if(data[i]==' ')
			break;
	}
	string str(data, 0, i);
	return str.substr(5);
}
	
string CRequestHandler::GetToUserName(const char* data, int size)
{
	cout<<"CRequestHandler::GetToUserName()"<<endl;
	int i = 0;
	for(; i<size; i++)
	{
		if(data[i]==' ')
			break;
	}
	string str(data, 0, i);
	return str.substr(3);
}

string CRequestHandler::GetMsgContent(const char* data, int size)
{
	cout<<"CRequestHandler::GetMsgContent()"<<endl;
	int i = 0;
	for(; i<size; i++)
	{
		if(data[i]==' ')
			break;
	}
	string temp(data, size);
	return temp.substr(i);
}
7. ChatServer.cpp(main函数)

#include "Server.h"
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void run()
{
	sigset_t new_mask;
	sigfillset(&new_mask);
	sigset_t old_mask;
	pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask);
	
	CIoServiceManager::Instance()->Start(2);
	CServer::Instance()->Start(9494);

	pthread_sigmask(SIG_SETMASK, &old_mask, 0);
	while (1)
	{
		sleep(1000);
	}
}

int main(int argc, char* argv[])
{
	pid_t chId, rebornId;
	chId = fork();

	if (chId == 0)
	{
		run();
		exit(0);
	}

	while (1)
	{
	    rebornId = wait(NULL);

        sleep(1);
        if(chId == rebornId)
        {
            chId = fork();
            if (chId == 0)
		    {
				run();
			    exit(0);
		    }
        }
		
	}
}

待续...

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

利用boost:asio写的简单聊天服务器四

二、客户端源代码 1. ChatClient.cpp (客户端main) #include #include #include #include #include #include ...

Muduo 网络编程示例之二:Boost.Asio 的聊天服务器

这是《Muduo 网络编程示例》系列的第二篇文章。 本文讲介绍一个与 Boost.Asio 的示例代码中的聊天服务器功能类似的网络服务程序,包括客户端与服务端的 muduo 实现。这个例子的主要目的是...

boost::asio学习之[六]简单聊天程序

#pragma once #include #include #include namespace ChatTest { class chat_message { public: e...

boost asio异步读写网络聊天程序客户端 实例详解

boost开发文档中实时聊天程序的客户端(加入了详细注释 方便理解)

boost asio异步读写网络聊天室【官方示例】

// // chat_message.hpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2010 Christopher M. Kohlhoff (ch...

Boost.Asio学习之简单的HTTP服务器

Boost.asio实现简单的HTTP服务器

简单的Boost::asio 高性能C/S服务器模型

Boost::Asio 在底层封装的了操作系统的高效I/O模型。实现了很高的并发量和吞吐量。其中操作系统主要实现了两种I/O模型Reactor和Proactor。 接下来探讨一下两种I/O多路复用模...

使用Boost.Asio写的多线程TCP转发代理服务器

http://www.cppblog.com/archiveman/archive/2010/03/05/108971.html 应用场景是这样的: 客户端和服务器在不同的网段内,它们之间...

boost asio中转服务器(TCP)

内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)