最近在研究網路相關的東西,發現之前對UDP的理解很弱,太依賴於TCP,依賴到甚至忘記了還有一個UDP的存在。於是在網上隨便搜了UDP socket編程的相關代碼和資料,發現有人寫的編程例子裡面居然還有connect的存在,我很無語。
UDP相對於TCP而言是不可靠的傳輸協議,在網路環境較差的情況下用TCP無疑是唯一的選擇,在網路環境很好的情況下,比如區域網路內部的訊息傳輸,進程與進程之間的通訊,UDP無疑是最好的選擇,UDP不僅在傳輸效率上有很大的優勢,我覺得更大的優勢在於它不需要維護串連,可以減少很多邏輯上的冗餘。
下面給大家看看一段代碼,UDP的簡單通訊。
服務端代碼,實現了echo功能:
/** @file UdpEchoServer.cpp * @note Hangzhou Hikvision System Technology Co., Ltd. All Rights Reserved. * @brief an udp server, echo what the client say. * * @author Zou Tuoyu * @date 2012/11/28 * * @note 記錄: * @note V1.0.0.0 建立 *///boost#include "boost/thread.hpp"#include "boost/asio.hpp"//stl#include <string>#include <iostream>using namespace std;int main(){boost::asio::io_service io_service;boost::asio::ip::udp::socket udp_socket(io_service);boost::asio::ip::udp::endpoint local_add(boost::asio::ip::address::from_string("10.64.49.70"), 7474);udp_socket.open(local_add.protocol());udp_socket.bind(local_add);char receive_buffer[1024] = {0};while (true){boost::asio::ip::udp::endpoint send_point;udp_socket.receive_from(boost::asio::buffer(receive_buffer, 1024), send_point);cout << "recv:" << receive_buffer << endl;udp_socket.send_to(boost::asio::buffer(receive_buffer), send_point);memset(receive_buffer, 0, 1024);}return 1;}
client端,輸入
//boost#include "boost/asio.hpp"//stl#include <iostream>using namespace std;int main(){boost::asio::io_service io_service;boost::asio::ip::udp::socket socket(io_service);boost::asio::ip::udp::endpoint end_point(boost::asio::ip::address::from_string("10.64.49.70"), 7474);socket.open(end_point.protocol());char receive_buffer[1024] = {0};while (true){cout << "input:";string input_data;cin >> input_data;cout << endl;try{socket.send_to(boost::asio::buffer(input_data.c_str(), input_data.size()), end_point);socket.receive_from(boost::asio::buffer(receive_buffer, 1024), end_point);cout << "recv:" << receive_buffer << endl;}catch (boost::system::system_error &e){cout << "process failed:" << e.what() << endl;}}}
本人對UDP的理解也很膚淺,有紕漏地方敬請指出,不甚感激。