-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathserver.cpp
More file actions
33 lines (29 loc) · 1.01 KB
/
server.cpp
File metadata and controls
33 lines (29 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//simple tcp socket server example with boost asio
//sudo apt install libboost-dev
//g++ -lpthread -lboost_system server.cpp -o server
#include <iostream>
#include <boost/asio.hpp>
//using namespace boost::asio
//using ip::tcp
using std::string;
using std::cout;
using std::endl;
int main()
{
boost::asio::io_service io_service;
//listen for new connection
boost::system::error_code ec;
boost::asio::ip::tcp::acceptor acceptor_(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 1234 ));
boost::asio::ip::tcp::socket socket_(io_service);//socket creation
acceptor_.accept(socket_);//waiting for connection
//read operation
boost::asio::streambuf buf;
boost::asio::read_until( socket_, buf, "\n",ec);
if(ec){std::cout<<ec.message()<<std::endl; return 1;}
string data = boost::asio::buffer_cast<const char*>(buf.data());
cout << data << endl;
//write operation
boost::asio::write( socket_, boost::asio::buffer(data) ,ec);
if(ec){std::cout<<ec.message()<<std::endl; return 1;}
return 0;
}