2016-01-12 41 views
0

我正在使用C++ boost asio来创建服务器客户端应用程序。C++ boost asio:bind:已在使用的地址

我遵循here的指导原则。

,我仍然不知道为什么我得到以下结果:

./server #ok 

./client # error 

绑定:地址已在使用


server.cpp:

#include <ctime> 
#include <iostream> 
#include <stdio.h> 
#include <string> 
#include <boost/array.hpp> 
#include <boost/asio.hpp> 

using boost::asio::ip::udp; 

struct UDP_Message 
{ 
    double number; 
}; 

int main() 
{ 
    try 
    { 
     boost::asio::io_service io_service; 
     udp::socket socket(io_service, udp::endpoint(udp::v4(), config::udp_port)); 
     UDP_Message message; 
     message.number=0; 
     for (;;) 
     { 
      udp::endpoint remote_endpoint; 
      message.number=message.number+0.001; 
      boost::system::error_code ignored_error; 
      socket.send_to(boost::asio::buffer(&message,sizeof(message)), 
      remote_endpoint, 0, ignored_error); 
     } 
    } 
    catch (std::exception& e) 
    { 
     std::cerr << e.what() << std::endl; 
    } 
    return 0; 
} 

client.cpp:

#include <ctime> 
#include <iostream> 
#include <stdio.h> 
#include <string> 
#include <boost/array.hpp> 
#include <boost/asio.hpp> 

using boost::asio::ip::udp; 

namespace config 
{ 
    const unsigned short udp_port=1414; 
} 

struct UDP_Message 
{ 
    double number; 
}; 

int main() 
{ 
    try 
    { 
     boost::asio::io_service io_service; 
     boost::asio::socket_base::reuse_address option(true); 
     udp::socket socket(io_service, udp::v4()); 
     socket.set_option(option); 
     socket.bind(udp::endpoint(udp::v4(), config::udp_port)); 
     UDP_Message message; 
     for (;;) 
     { 
      boost::array<char, 1> recv_buf; 
      udp::endpoint remote_endpoint; 
      boost::system::error_code error; 
      socket.receive_from(boost::asio::buffer(recv_buf), 
      remote_endpoint, 0, error); 
      if (error && error != boost::asio::error::message_size) 
      throw boost::system::system_error(error); 
      std::memcpy(&message,recv_buf.data(),sizeof(message)); 
      std::cout<<message.number<<std::endl; 
     } 
    } 
    catch (std::exception& e) 
    { 
     std::cerr << e.what() << std::endl; 
    } 
    return 0; 
} 
+0

我相信任何使用boost :: asio的人都应该通过使用裸BSD套接字例程来学习套接字编程的“绳索”。 – SergeyA

+0

@TNW得到了[这里](http://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/tutorial/tutdaytime5/src.html)并试图将它们分开。 – ar2015

+0

'recv_buf'数组看起来有点偏小。 – molbdnilo

回答

1

您正在尝试到这两个客户端和服务器绑定到同一个端口,udp_port = 1414。这是你不能做的。

+0

,但他们必须发送和收听相同的端口 – ar2015

+0

如果你搞砸了服务器和客户端代码(如其他评论所暗示),我的答案是不相关的。请张贴正确的代码,我会相应地编辑我的答案。 – SergeyA

+0

我从这里得到的代码:http://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/tutorial/tutdaytime5/src.html – ar2015