2016-01-12 38 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