boost::asio伺服器處理多個客戶端連線(客戶端程式)
//客戶端程式
//
// main.cpp
// tcpserver
// Created by suxianbin on 2018/9/15.
// Copyright © 2018 suxianbin. All rights reserved.
//
//
//
// blocking_tcp_echo_server.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/timer/timer.hpp>
#include <thread>
using namespace boost::asio;
using namespace std;
using namespace boost;
io_service service;
class talk_to_server
{
public:
talk_to_server(string name):m_sock(service),user(name),already_read(0){}
void connect(ip::tcp::endpoint ep)
{
m_sock.connect(ep);
}
string username(){return this->user;}
ip::tcp::socket& sock(){return this->m_sock;}
bool read_complete(const boost::system::error_code &erro,size_t bytes)
{
if(erro)return 0;
already_read=bytes;
bool found=find(buff,buff+bytes,'*')<buff+bytes;
return found?0:1;
}
void loop()
{
while(true)
{
//write_request();
read_answer();
}
}
void write(string msg)
{
m_sock.write_some(buffer(msg));
}
void write_request()
{
write("to do somgthing");
//std::thread::sleep
boost::this_thread::sleep(boost::posix_time::millisec(1000));
}
void read_answer()
{
already_read=0;
already_read+=m_sock.read_some(buffer(buff));
process_msg();
}
void process_msg()
{
bool found_enter=find(buff,buff+already_read,'*')<buff+already_read;
if(!found_enter)return;
size_t pos=find(buff,buff+already_read,'*')-buff;
string msg(buff,pos);
cout<<msg<<endl;
}
private:
ip::tcp::socket m_sock;
char buff[1024];
size_t already_read;
string msg;
string user;
};
int main()
{
io_service service;
ip::tcp::endpoint ep=ip::tcp::endpoint(ip::address::from_string("127.0.0.1"),8080);
talk_to_server *client=new talk_to_server("eric");
client->connect(ep);
client->loop();
return 0;
}
//伺服器程式見下文