同步和异步UDP使用方法

  同步和异步Socket的区别是,同步Socket会阻塞当前进程,而异步Socket则不会。

  首先,一个最简单的同步UDP收发程序实例。可以看到,发送调用Send()函数之后,开始调用Receive接收,这个时候程序会一直在这里等待,直到收到数据。

  

using System;
using System.Net.Sockets;
using System.Net;
using System.Text;

public class UdpClientTest
{
    public static void Main()
    {
        UdpClient udpClient = new UdpClient(6000);    //侦听本地端口
        IPEndPoint host = new IPEndPoint(IPAddress.Parse("192.168.191.1"),7000);    //这里是目标主机和端口
        Byte[] msg = new UTF8Encoding(true).GetBytes("Hee How are U?");
        udpClient.Send(msg, msg.Length, host);

        IPEndPoint remoteHost = new IPEndPoint(IPAddress.Any,0);
        Byte[] receivedBytes = udpClient.Receive(ref remoteHost);
        string returnData = Encoding.ASCII.GetString(receivedBytes);
        Console.WriteLine("This is message you received is :"+returnData.ToString());
        Console.WriteLine("This is was sent form : "+remoteHost.Address.ToString() + " port number " + remoteHost.Port.ToString());

        udpClient.Close();
    }
}

  下面是一个异步UDP的实例,

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;

namespace Test
{
    class UdpServer
    {
        public Socket serverSocket;
        public byte[] dataStream;
        public byte[] receivedBytes;
        public EndPoint epSender;

        // 关闭前一个窗口的回调函数
        public delegate void OnDataReceived();
        public event OnDataReceived onDataReceive;

        public UdpServer()
        {
            this.dataStream = new byte[10240];
        }

        public void Open(int port)
        {
            this.serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint serverPoint = new IPEndPoint(IPAddress.Any, port);
            this.serverSocket.Bind(serverPoint);
        }

        public void Close()
        {
            this.serverSocket.Shutdown(SocketShutdown.Both);
            this.serverSocket.Close();

            this.serverSocket.Shutdown(SocketShutdown.Both);
            this.serverSocket.Close();
        }

        public void Listen()
        {
            try
            {
                IPEndPoint clientPoint = new IPEndPoint(IPAddress.Any, 0);
                this.epSender = (EndPoint)clientPoint;
                this.serverSocket.BeginReceiveFrom(this.dataStream, 0,
                                        this.dataStream.Length,
                                        SocketFlags.None,
                                        ref epSender,
                                        new AsyncCallback(ReceiveData),
                                        epSender);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "UDP连接创建失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ReceiveData(IAsyncResult asyncResult)
        {
            try
            {
                int recv_len = serverSocket.EndReceiveFrom(asyncResult, ref epSender);
                this.serverSocket.BeginReceiveFrom(this.dataStream, 0,
                                        this.dataStream.Length,
                                        SocketFlags.None,
                                        ref epSender,
                                        new AsyncCallback(ReceiveData),
                                        epSender);

                receivedBytes = new byte[recv_len];
                Array.Copy(dataStream, 0, receivedBytes,0,recv_len);

                Console.WriteLine("got "+recv_len.ToString() + " Bytes");
                Console.WriteLine("str is: "+ Encoding.ASCII.GetString(dataStream,0,recv_len));

                onDataReceive();
            }
            catch (Exception ex)
            {
               MessageBox.Show(ex.Message, "UDP接收异常", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /*
        public void SendTo(IPEndPoint dstEndPoint, byte[] byteData,int length) {
            EndPoint dstHost = (EndPoint)dstEndPoint;
            // Begin sending the data to the remote device.
            this.serverSocket.BeginSendTo(byteData, 0, length,
                    SocketFlags.None, dstHost,
            new AsyncCallback(SendCallback), this.serverSocket);
        }*/

        private void SendTo(IPEndPoint dstEndPoint, string text) {
            byte[]    byteData = Encoding.ASCII.GetBytes(text);
            EndPoint dstHost = (EndPoint)dstEndPoint;
            // Begin sending the data to the remote device.
            this.serverSocket.BeginSendTo(byteData, 0, byteData.Length,
                    SocketFlags.None, dstHost,
            new AsyncCallback(SendCallback), this.serverSocket);
        }

        private void SendCallback(IAsyncResult ar) {
            try {
                // Retrieve the socket from the state object.
                Socket handler = (Socket) ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);
                Console.WriteLine("Sent {0} bytes to client.", bytesSent);

                //handler.Shutdown(SocketShutdown.Both);
                //handler.Close();

            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "UDP发送异常", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        public static void Main()
        {
            IPEndPoint dstPoint = new IPEndPoint(IPAddress.Parse("192.168.65.230"),7000);//发送到本地7000端口
            UdpServer udpServer = new UdpServer();
            udpServer.Open(6000);    //本地侦听6000端口
            udpServer.Listen();
            udpServer.SendTo(dstPoint, "Hello World!!!");

            while(true)
            {

            }
        }
    }
}
时间: 2024-08-05 11:16:13

同步和异步UDP使用方法的相关文章

Ajax同步、异步和相应数据格式

(一)同步和异步 xhr.open()方法第三个参数要求传入的是一个 布尔值,其作用就是设置此次请求是否采用异步方式执行 默认为 true异步 可修改为 false为同步. 异步代码举栗: 1 console.log('before ajax') 2 var xhr = new XMLHttpRequest() 3 // 默认第三个参数为 true 意味着采用异步方式执行 4 xhr.open('GET', '/time', true) 5 xhr.send(null) 6 xhr.onread

异步Udp监听关闭 出现异常,访问已释放的资源或者其他错误的解决方法

在开发异步Udp程序的过程中,通常在关闭UDP的时候回遇到诸如socket 访问已释放的资源之类的异常,如下简单操作下: 1 Udp的监听 2 this.serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 3 this.serverSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Reus

C#网络编程系列文章(五)之Socket实现异步UDP服务器

原创性声明 本文作者:小竹zz 本文地址http://blog.csdn.net/zhujunxxxxx/article/details/44258719 转载请注明出处 本文介绍 在.Net中,System.Net.Sockets 命名空间为需要严密控制网络访问的开发人员提供了 Windows Sockets (Winsock) 接口的托管实现.System.Net 命名空间中的所有其他网络访问类都建立在该套接字Socket实现之上,如TCPClient.TCPListener 和 UDPCl

C#网络编程系列文章(七)之UdpClient实现异步UDP服务器

原创性声明 本文作者:小竹zz 本文地址http://blog.csdn.net/zhujunxxxxx/article/details/44258719 转载请注明出处 本文介绍 UdpClient 类在同步阻塞模式中为发送和接收无连接的 UDP 数据包而提供了简单的方法.因为 UDP 是一种无连接的传输协议,所以你不需要在发送和接收数据之前建立任何远程主机连接.你只需要按照下列方式来建立默认的远程主机选项: 使用远程主机名称和端口号作为参数来创建 UdpClient 类的实例. 创建 Udp

【Mocha.js 101】同步、异步与 Promise

前情提要 在上一篇文章<[Mocha.js 101]Mocha 入门指南>中,我们提到了如何用 Mocha.js 进行前端自动化测试,并做了几个简单的例子来体验 Mocha.js 给我们带来的便利. 在本篇文章中,我们将了解到 Mocha.js 的同步/异步测试,以及如何测试 Promise. 同步代码测试 在上一篇文章中,其实我们已经学会了如何测试同步代码.今天,我们 BDD 风格编写一个测试: var should = require( 'should' ); var Calculator

socket阻塞与非阻塞,同步与异步、I/O模型,select与poll、epoll比较

1. 概念理解 在进行网络编程时,我们常常见到同步(Sync)/异步(Async),阻塞(Block)/非阻塞(Unblock)四种调用方式: 同步/异步主要针对C端: 同步:      所谓同步,就是在c端发出一个功能调用时,在没有得到结果之前,该调用就不返回.也就是必须一件一件事做,等前一件做完了才能做下一件事. 例如普通B/S模式(同步):提交请求->等待服务器处理->处理完毕返回 这个期间客户端浏览器不能干任何事 异步:      异步的概念和同步相对.当c端一个异步过程调用发出后,调

Python 中的进程、线程、协程、同步、异步、回调

进程和线程究竟是什么东西?传统网络服务模型是如何工作的?协程和线程的关系和区别有哪些?IO过程在什么时间发生? 在刚刚结束的 PyCon2014 上海站,来自七牛云存储的 Python 高级工程师许智翔带来了关于 Python 的分享<Python中的进程.线程.协程.同步.异步.回调>. 一.上下文切换技术 简述 在进一步之前,让我们先回顾一下各种上下文切换技术. 不过首先说明一点术语.当我们说"上下文"的时候,指的是程序在执行中的一个状态.通常我们会用调用栈来表示这个状

AJAX同步和异步

请求方式,分为GET与POST: GET 最为常见的HTTP请求,普通上网浏览页面就是GET.GET方式的参数请求直接跟在URL后,以问号开始.(JS中用window.location.search获得).参数可以用encodeURIComponent进行编码,使用方式: var EnParam = encodeURIComponent(param); URL只支持大约2K的长度,即2048字符数:使用GET进行AJAX请求时候会缓存导致出现的页面不是正确的,一般方法加random参数值:aja

HTTP请求中同步与异步有什么不同

普通的B/S模式就是同步,而AJAX技术就是异步,当然XMLHttpReques有同步的选项. 同步:提交请求->等待服务器处理->处理完毕返回.这个期间客户端浏览器不能干任何事. 异步: 请求通过事件触发->服务器处理(这是浏览器仍然可以作其他事情)->处理完毕. 举个生动的例子吧: 同步就是你叫我去吃饭,我听到了就和你去吃饭:如果没有听到,你就不停的叫,直到我告诉你听到了,才一起去吃饭. 异步就是你叫我,然后自己去吃饭,我得到消息后可能立即走,也可能等到下班才去吃饭.豪享博娱乐