boost aio多线程服务器与unity 程序连接 测试代码

#  define _WIN32_WINNT 0x0501
#include <string.h>            //memset//typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;

#define TRUE             1
#define FALSE             0
static int count111 = 0;
static time_t oldtime = 0, nowtime = 0;

#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
#include <iostream>
using namespace std;
using boost::asio::ip::tcp;

class io_service_pool
    : public boost::noncopyable
{
public:

    explicit io_service_pool(std::size_t pool_size)
        : next_io_service_(0)
    {
        for (std::size_t i = 0; i < pool_size; ++ i)
        {
            io_service_sptr io_service(new boost::asio::io_service);
            work_sptr work(new boost::asio::io_service::work(*io_service));
            io_services_.push_back(io_service);
            work_.push_back(work);
        }
    }

    void start()
    {
        for (std::size_t i = 0; i < io_services_.size(); ++ i)
        {
            boost::shared_ptr<boost::thread> thread(new boost::thread(
                boost::bind(&boost::asio::io_service::run, io_services_[i])));
            threads_.push_back(thread);
        }
    }

    void join()
    {
        for (std::size_t i = 0; i < threads_.size(); ++ i)
        {
            threads_[i]->join();
        }
    }

    void stop()
    {
        for (std::size_t i = 0; i < io_services_.size(); ++ i)
        {
            io_services_[i]->stop();
        }
    }

    boost::asio::io_service& get_io_service()
    {
        boost::mutex::scoped_lock lock(mtx);
        boost::asio::io_service& io_service = *io_services_[next_io_service_];
        ++ next_io_service_;
        if (next_io_service_ == io_services_.size())
        {
            next_io_service_ = 0;
        }
        return io_service;
    }

private:
    typedef boost::shared_ptr<boost::asio::io_service> io_service_sptr;
    typedef boost::shared_ptr<boost::asio::io_service::work> work_sptr;
    typedef boost::shared_ptr<boost::thread> thread_sptr;

    boost::mutex mtx;

    std::vector<io_service_sptr> io_services_;
    std::vector<work_sptr> work_;
    std::vector<thread_sptr> threads_;
    std::size_t next_io_service_;
};

boost::mutex cout_mtx;
int packet_size = 0;
enum {MAX_PACKET_LEN = 4096};

class session
{
public:
    session(boost::asio::io_service& io_service)
        : socket_(io_service)
        , recv_times(0)
    {
    }

    virtual ~session()
    {
        boost::mutex::scoped_lock lock(cout_mtx);
    }

    tcp::socket& socket()
    {
        return socket_;
    }

    inline void start()
    {

        socket_.async_read_some(boost::asio::buffer(data_, MAX_PACKET_LEN),
            boost::bind(&session::handle_read, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    }

    void handle_read(const boost::system::error_code& error, size_t bytes_transferred)
    {
        if (!error)
        {
            ++ recv_times;


            count111 ++;

            struct tm *today;
            time_t ltime;
            time( &nowtime );

            if(nowtime != oldtime){
                printf("%d\n", count111);
                oldtime = nowtime;
                count111 = 0;
            }


            boost::asio::async_write(socket_, boost::asio::buffer(data_, bytes_transferred),
                boost::bind(&session::handle_write, this, boost::asio::placeholders::error));

 

        }
        else
        {
            delete this;
        }
    }

    void handle_write(const boost::system::error_code& error)
    {
        if (!error)
        {
            start();
        }
        else
        {
            delete this;
        }
    }

private:
    tcp::socket socket_;
    char data_[MAX_PACKET_LEN];
    int recv_times;
};

class server
{
public:
    server(short port, int thread_cnt)
        : io_service_pool_(thread_cnt)
        , acceptor_(io_service_pool_.get_io_service(), tcp::endpoint(tcp::v4(), port))
    {
        session* new_session = new session(io_service_pool_.get_io_service());
        acceptor_.async_accept(new_session->socket(),
            boost::bind(&server::handle_accept, this, new_session, boost::asio::placeholders::error));
    }

    void handle_accept(session* new_session, const boost::system::error_code& error)
    {
        if (!error)
        {
            new_session->start();
        }
        else
        {
            delete new_session;
        }

        new_session = new session(io_service_pool_.get_io_service());
        acceptor_.async_accept(new_session->socket(),
            boost::bind(&server::handle_accept, this, new_session, boost::asio::placeholders::error));
    }

    void run()
    {
        io_service_pool_.start();
        io_service_pool_.join();
    }

private:

    io_service_pool io_service_pool_;
    tcp::acceptor acceptor_;
};

 


int main()
{

    //boost
 int i=0;
 cout<<i<<endl;
    server s(554, 1);
    s.run();

    while(true)
    {
  int j=1000;
  boost::this_thread::sleep(boost::posix_time::seconds(1000));


     }
 system("pause");
    return 0;
}

注意boost代码使用asio需要编译lib后才能用

 

unity 用c#socket 马马虎虎能连

using UnityEngine; 
using System.Collections; 
using System.ComponentModel; 
using System; 
using System.Text; 
using System.Net;  
using System.Net.Sockets; 
using System.Threading;


public class CtoS : MonoBehaviour {
 public string SendM= "-(00)-";  
 public string server = "127.0.0.1"; 
 private Socket socket;   
 public GUIText Test;

 // Use this for initialization
 void Start () {
  try 
  {  
   /*Connect*/ 
   print("start");
   socket = new Socket ( AddressFamily.InterNetwork ,
                        SocketType.Stream , ProtocolType.Tcp);  
   IPEndPoint tempRemoteIP = new IPEndPoint
    (IPAddress.Parse(server), 554);  
   EndPoint epTemp = (EndPoint)tempRemoteIP; 
   socket.Connect(epTemp); 
   print("Success Connect");
   /*Send*/  
   Byte[] bytesSent = Encoding.ASCII.GetBytes(SendM); 
   socket.Send(bytesSent,bytesSent.Length,0); 
   
   /*Received*/  
   Byte[] bytesReceived = new Byte[256]; 
   int bytes = 0;  
   string page = "Server: Success Connect " + server + ":\r\n"; 
   do  
   {  
    bytes = socket.Receive(bytesReceived,
                           bytesReceived.Length, 0);  
    page = page + Encoding.ASCII.GetString(bytesReceived, 0,
                                           bytes); 
   }  
   while (bytes > 0); 
   Test.text = page; 
   
  }  
  catch (Exception e)  
   
   
  {  
   print(e);    
  }    


 }
 
 // Update is called once per frame
 void Update () {
 
 }
}

 


 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值