write by http://blog.csdn.net/bojie5744 bj_末雨
udp sender
- #include "stdafx.h"
- #include <string>
- #include <boost/asio.hpp>
- using namespace std;
- using namespace boost::asio;
- int _tmain(int argc, _TCHAR* argv[])
- {
- io_service my_io_service; // ip::udp::endpoint my_local_enpoint(ip::udp::v4(),0);/*another way to create endpoint*/
- // my_udp_socket.open(my_login_server_endpoint.protocol());
- // my_udp_socket.bind(my_local_enpoint);
- ip::udp::endpoint local_endpoint(ip::udp::v4(), 7777);//create endpoint,this a local endpoint
- ip::udp::endpoint remote_endpoint(ip::address_v4::from_string("127.0.0.1"), 2300);//create a remote endpoint
- //don't fill (ip::udp::v4()) in the first parameter,it will cause that the contents are seny out the failure!
- ip::udp::socket socket(my_io_service, local_endpoint);//create socket and bind the endpoint
- char *send_data = "hello! my name is Bojie. Can you see me?";/*the contents to be sent*/
- try
- {
- while (1)
- {
- Sleep(500);
- socket.send_to(buffer(send_data, strlen(send_data) + 1/*the size of contents*/), remote_endpoint);
- }
- }
- catch (std::exception& e)//to get the error when sending
- {
- std::cerr << e.what() << std::endl;
- }
- return 0;
- }
udp recivcer
- #include "stdafx.h"
- #include <string>
- #include <boost/asio.hpp>
- using namespace std;
- using namespace boost::asio;
- int _tmain(int argc, _TCHAR* argv[])
- {
- io_service my_io_service;
- ip::udp::endpoint local_endpoint(ip::address_v4::from_string("127.0.0.1"), 2300);//create a local endpoint
- ip::udp::endpoint romote_endpoint; //this enpoint is used to store the endponit from remote-computer
- ip::udp::socket socket(my_io_service, local_endpoint);//create socket and bind the endpoint
- char buffer[40000];
- int nAdd = 0;
- while (1)
- {
- memset(buffer, 0, 40000);//to initialize variables
- nAdd++;
- socket.receive_from(boost::asio::buffer(buffer, 40000), romote_endpoint);//receive data from remote-computer
- printf("recv %d datapacket:%s ",nAdd, buffer);
- }
- return 0;
- }
see the gif