[Wp8.1 (runtime)] UDP protocol for socket programming

Source: Internet
Author: User

13.3 socket programming-UDP protocol

Both UDP and TCP are socket programming protocols. However, unlike TCP, UDP does not provide timeout retransmission, error retransmission, and other functions, that is, it is an unreliable protocol. UDP is applicable to applications that transmit only a small amount of data at a time and do not require high reliability. Since UDP is an unreliable network protocol, what is its value or necessity? In fact, in some cases, UDP may become very useful. Because UDP has a speed advantage beyond the reach of TCP. Although various security protection functions are embedded in the TCP protocol, a large amount of system overhead will be occupied during actual execution, and the speed will undoubtedly be seriously affected. In contrast, UDP eliminates the information reliable transfer mechanism and transfers security and sorting functions to upper-layer applications, greatly reducing the execution time and ensuring the speed. In Windows Phone, UDP communication uses the mongoramsocket class to send, receive, and listen to messages, next, let's take a look at how to Implement UDP Communication in Windows Phone.

13.3.1 send and receive messages

There is a difference between sending and receiving messages using UDP protocol and TCP protocol. UDP does not have to be connected. It can send and receive messages directly through the host address. The same is true for sending and receiving messages using UDP. It depends on the datawriter class and the datareader class to send and receive data separately. Next, let's take a look at the two methods of sending and receiving messages using UDP in Windows Phone.

(1) Use the host name and port number to send and receive messages directly.

Create an initramsocket Class Object, call the getoutputstreamasync method to obtain the ioutputstream object of the output stream, and then use the ioutputstream object to create a datawriter object to send messages. Receive messages directly subscribe to the messagereceived event of the initramsocket object to receive messages, and use the datareader object to get the message content. The sample code is as follows:

    // 主机名    HostName hostName = new HostName("localhost");    DatagramSocket datagramSocket = new DatagramSocket();    // 订阅接收消息的事件    datagramSocket.MessageReceived += datagramSocket_MessageReceived;    // 获取输出流    IOutputStream outputStream = await datagramSocket.GetOutputStreamAsync(hostName, "22112");    // 创建DataWriter对象发送消息    DataWriter writer = new DataWriter(datagramSocket.OutputStream);    writer.WriteString("test");    await writer.StoreAsync();    // 接收消息的事件处理程序    async void datagramSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)    {        // 获取DataReader对象,读取消息内容        DataReader dataReader = args.GetDataReader();        uint length = dataReader.UnconsumedBufferLength;        string content = dataReader.ReadString(length);    }

 

(2) Connect to the socket first.Resend and receive messages

The initramsocket class also provides the connectasync method to handle socket connections. After successful connections, you can use this initramsocket object to send messages, messages are received in the same way as messages in the first method. The sample code is as follows:

    // 创建DatagramSocket    DatagramSocket datagramSocket = new DatagramSocket();    datagramSocket.MessageReceived += datagramSocket_MessageReceived;    // 连接服务器    await datagramSocket.ConnectAsync(new HostName("localhost"), "22112");    // 发送消息    DataWriter writer = new DataWriter(datagramSocket.OutputStream);    writer.WriteString("test");    await writer.StoreAsync();

 

13.3.2 UDP server listens to messages

UDP is also implemented using the rabbitramsocket class to implement the server-side message listening function. The implementation steps are as follows:

(1) register the messagereceived event of the initramsocket object to receive messages (note the difference between the event and the TCP connectionreceived event );

(2) Use the bindservicenameasync method to establish a listener for the local server;

(3) use the getoutputstreamasync method to pass in the server address and port number, obtain the ioutputstream object, and create a datawriter object to send messages to the client.

The following is an example of UDP protocol server-side message listening code:

    // 创建DatagramSocket对象,调用BindServiceNameAsync方法绑定服务    DatagramSocket datagramSocket = new DatagramSocket();    // 订阅MessageReceived事件监听客户端发送过来的消息    datagramSocket.MessageReceived += datagramSocket_MessageReceived;    await datagramSocket.BindServiceNameAsync("22112");    // MessageReceived事件的处理程序,获取到客户端的地址后可以向客户端发送消息    async void datagramSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)    {        // 读取客户端发送过来的消息        DataReader dataReader = args.GetDataReader();        uint length = dataReader.UnconsumedBufferLength;        string content = dataReader.ReadString(length);        IOutputStream outputStream = await sender.GetOutputStreamAsync(                args.RemoteAddress,                args.RemotePort);        DataWriter writer = new DataWriter(outputStream);        writer.WriteString(content + "(服务器发送)" );        await writer.StoreAsync();    }

This article comes from the introduction to Windows Phone 8.1 Application Development

Wp8.1 runtime articles: http://www.cnblogs.com/linzheng/p/3998037.html

Source code download: http://vdisk.weibo.com/s/zt_pyrfNHb99O

Welcome to my weibo @ WP Lin Zheng public account: Wp Development (No.: wpkaifa)

Wp8.1 technical exchange group: 372552293

[Wp8.1 (runtime)] UDP protocol for socket programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.