c#异步通讯 tcp连接任意ip怎么修改

c#异步通讯 tcp连接任意ip怎么修改,本机可以工作,但是把Dns.GetHostName()改成指定的ipv6地址连接不上

private int maxPlayingTables;
        private CheckBox[,] checkBoxGameTables;
        private TcpClient client = null;
        private Service service;
        private StreamWriter sw;
        private StreamReader sr;
        private BinaryReader br;
        private BinaryWriter bw;
        bool exitWhile = false;

        private FormPlaying formPlaying;

        private bool isConnected = false; //是否连接成功

        BackgroundWorker connectWork = new BackgroundWorker();
        //是否正常退出接收线程
        private bool normalExit = false;
        //命令是否来自服务器
        private bool isReceiveCommand = false;
        //所坐的游戏桌座位号,-1表示未入座,0表示坐到黑方,1表示坐到白方
        private int side = -1;
        public FormRoom()
        {
            InitializeComponent();
            connectWork.DoWork += new DoWorkEventHandler(connectWork_DoWork);
            connectWork.RunWorkerCompleted +=
                new RunWorkerCompletedEventHandler(connectWork_RunWorkerCompleted);
        }
        private void FormRoom_Load(object sender, EventArgs e)
        {
            Random r = new Random((int)DateTime.Now.Ticks);
            textBoxName.Text = "Player" + r.Next(1, 100);
            maxPlayingTables = 0;
            textBoxLocal.ReadOnly = true;
            textBoxServer.ReadOnly = true;
        }

        /// <summary>异步方式与服务器进行连接</summary>
        void connectWork_DoWork(object sender, DoWorkEventArgs e)
        {
            client = new TcpClient();
            //此处为方便演示,实际使用时要将Dns.GetHostName()改为服务器域名
            //IAsyncResult result = client.BeginConnect(Dns.GetHostName(), 51888,null,null);
            //while (result.IsCompleted == false)
            //{
            //    Thread.Sleep(100);
            ////    
            //}
            try
            {
                // client.EndConnect(result);
                client = new TcpClient(Dns.GetHostName(), 51888);
                e.Result = "login";
            }
            catch (Exception ex)
            {
                e.Result = ex.Message;
                return;
            }
        }
        /// <summary>异步方式与服务器完成连接操作后的处理</summary>
        void connectWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result.ToString() == "login")
            {

                isConnected = true;

                groupBox1.Visible = true;
                textBoxLocal.Text = client.Client.LocalEndPoint.ToString();
                textBoxServer.Text = client.Client.RemoteEndPoint.ToString();
                buttonConnect.Enabled = false;
                //获取网络流
                NetworkStream netStream = client.GetStream();
                //sr = new StreamReader(netStream, System.Text.Encoding.UTF8);
                //sw = new StreamWriter(netStream, System.Text.Encoding.UTF8);
                br = new BinaryReader(netStream);
                bw = new BinaryWriter(netStream);
                service = new Service(listBox1, bw);
                service.SendToServer("Login," + textBoxName.Text.Trim());
                Thread threadReceive = new Thread(new ThreadStart(ReceiveData));
                threadReceive.IsBackground = true;
                threadReceive.Start();
            }
            else
            {
                //AddStatus("连接失败:" + e.Result);
                MessageBox.Show("与服务器连接失败", "",
                   MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
                //buttonConnect.Enabled = true;
            }
        }

        /// <summary>【登录】按钮的Click事件</summary>
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            buttonConnect.Enabled = false;
            connectWork.RunWorkerAsync();
            //try
            //{
            //    //仅作本机测试,实际使用时要将Dns.GetHostName()改为服务器域名
            //    client = new TcpClient(Dns.GetHostName(), 51888);

            //}
            //catch
            //{
            //    MessageBox.Show("与服务器连接失败", "",
            //        MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}
            //groupBox1.Visible = true;
            //textBoxLocal.Text = client.Client.LocalEndPoint.ToString();
            //textBoxServer.Text = client.Client.RemoteEndPoint.ToString();
            //buttonConnect.Enabled = false;
            ////获取网络流
            //NetworkStream netStream = client.GetStream();
            //sr = new StreamReader(netStream, System.Text.Encoding.UTF8);
            //sw = new StreamWriter(netStream, System.Text.Encoding.UTF8);
            //service = new Service(listBox1, sw);
            ////登录服务器,获取服务器各桌信息
            ////格式:Login,昵称
            //service.AsyncSendToServer("Login," + textBoxName.Text.Trim());
            //Thread threadReceive = new Thread(new ThreadStart(ReceiveData));
            //threadReceive.Start();
        }

后面处理接受数据的就不贴了,

0

1个回答

TcpClient client = new TcpClient(AddressFamily.InterNetworkV6);
client.Connect("fe80::14d8:a209:89e6:c162%14", 9900);

0
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
C# TCP/IP 异步通讯
为什么调用 Recevice 的时候 我的函数 ReceiveCallback 在执行的时候 只能执行 if (bytesRead > 0) 里面的 执行不了else 里面的rn回调函数 里面的 再次 执行 client.BeginReceive函数 也进不去,就是继续读取似乎不行,加了断点也没有用rnrnprivate void Receive(Socket client) rn rn // 构造容器state. rn StateObject state = new StateObject(); rn state.workSocket = client; rn // 从远程目标接收数据. rn rn client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);rn // sendDone.WaitOne();rn Thread.Sleep(200); rn rn private void ReceiveCallback(IAsyncResult ar) rn rn // 从输入参数异步state对象中获取state和socket对象 rn StateObject state = (StateObject)ar.AsyncState; rn Socket client = state.workSocket;rn //从远程设备读取数据 rn // int bytesRead = 0;rn int bytesRead = client.EndReceive(ar); rn if (bytesRead > 0) rn rn state.sb.Append(Encoding.GetEncoding("GB2312").GetString(state.buffer, 0, bytesRead));rn response = state.sb.ToString();rn // 继续读取. rn tryrn rn client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);rn rn catch (Exception e)rn rn rn rn rn else //为什么执行不了这里面的语句语句rn rn receiveDone.Set(); // 所有数据读取完毕. rn if (state.sb.Length > 1) rn rn response = state.sb.ToString(); rn rn // 所有数据读取完毕的指示信号. rn rn
c# tcp异步通讯框架
自己写的TCP异步通讯框架,对原来的进行封装,使得收发消息方便。
C# TCP助手异步通讯
C# 使用TCP助手类(TcpListener和TcpClient)的异步通讯例程,服务器端和客户端收发信息。
tcp异步通讯
Tcp异步通讯源码,study-ing
异步TCP通讯程序
异步TCP通讯程序 异步 TCP socket 通讯 程序
TCP 异步通讯库
TCP 异步通讯类包括服务器和客户端测试demo,客户端可同时链接多个服务器,客户端发送数据到服务器失败会保存发送失败数据成文件,待服务器正常后,重新发送。提供AEBellTCPServerSDK.dll 和 AEBellTCPClientSDK.dll 使用者可简单调用接口完成tcp数据通讯功能。编译环境VS2008 需要打VS2008SP1补丁。
C#局域网聊天系统(TCP异步通讯)
本系统采用TCP异步方式通讯,代码用到了委托和事件,以及透明窗体不规则窗体的制作,对初学者学习较好
C# TCP异步通讯框架封装
最近用c#写了一个TCP异步通讯框架TCPHelper,用于服务端客户端通讯,采用异步和事件驱动的方式,使用者只需要初始化和装载事件即可使用,框架图粗略如下所示: 使用如下:(本文框架及实例下载地址) 服务端using System; using System.Collections.Generic; using System.Linq; using System.Text; using S
C#的TCP异步SOCKET通讯类
C#的TCP异步SOCKET通讯类 C# TCP 异步 SOCKET 通讯 类,非常实用的一个类
C#异步TCP Socket通讯代码
C#开发的TCP异步通讯,采用异步方式,通讯高效,并提供记录日志功能,可直接用到自己工程中使用。
C#建立TCP/IP连接
C#建立TCP/IP连接在C/S模式下做网络信号传输,使用TCP/IP协议是首选。 其传输机制: 首先服务端与客户端建立套接字(socket)连接,建立完套接字后,服务端与客户端通过套接字进行数据传输。通常服务端和客户端需要各开启一个线程进行数据的接收。1.构建连接首先服务端开启套接字监听服务,然后客户端根据服务器的IP、端口进行连接。1.1服务端开启套接字Socket serverSocket
TCP/IP通讯demo
包括C\C#\MATLAB程序编写的与肌电仪通讯的demo,可以用来学习客户端与服务器通讯
TCP/IP通讯技术
MFC例子TCP/IP通讯技术
tcp/ip通讯的问题!!!!!
我用.net framwork的.net.sockets实现通讯功能rn可是测试的是的时候,我一开始lisener.start操作,客户端虽然可以接受服务器端的信息,可是服务器短缺处于不响应状态,这是怎么回事情呢,希望哪位老大帮帮小弟。rn源代码如下:rn(我通过timer控件每0.5s监视一下有无连接请求)rn listener.Start() '//Begin to listen the client rn Dim client As TcpClient = listener.AcceptTcpClientrn Label1.Text = "Connected Accepted"rn Dim ns As NetworkStream = client.GetStreamrn Dim byteMessage() As Byte = Encoding.ASCII.GetBytes(TextBox1.Text)rn '//向客户端写入发送信息rn Tryrn ns.Write(byteMessage, 0, byteMessage.Length)rn ns.Close()rn client.Close()rn Catchrn MsgBox("It's wrong")rn Finallyrn listener.Stop() '//Stop listenning rn End Tryrnrn客户端rnConst portNum As Integer = 13rn Const hostName As String = "127.0.0.1"rn Tryrn Label1.Text = "Try to connect to " + hostName + ":" + portNum.ToString()rn Dim client As New TcpClient()rn client.Connect(hostName, portNum)rn Dim ns As NetworkStream = client.GetStream()rn Dim bytes(1024) As Bytern Dim bytesRead As Integer = ns.Read(bytes, 0, bytes.Length)rn Label1.Text = Encoding.ASCII.GetString(bytes, 0, bytesRead)rn client.Close()rn Catchrn MsgBox("It's wrong ")rnrn End Try
TCP/IP长连接通讯
URL 1 : http://www.cosms.cn/sms/getMD5st/rnURL 2 : http://www.cosms.cn/sms/MD5/?str=testrnrn要求取得URL 1 和 URL 2 生成的字符串,[color=#FF0000][b]而且必须使用同一个 TCP/IP 长连接通讯[/b][/color]rnrn由于要求使用同一个TCP/IP长连接通讯,因此不能用webClient和HttpWebRequest来获取rnrn所以我想只有用TcpClient了rnrn我用了TcpClient,但问题出来了,问题是:只能接受第一次send的信息,第二次接受不到,咋办?rnrn我socket编程不熟,各位大虾们帮忙了(最好有代码给我参考下),急哦。。rn
TCP/IP通讯问题
我用TCP/IP建立了C/S结构。rn客户端首先发数据,服务端等40MS后给客户端发数据。rn客户端没100MS检查是否收到数据,收到就给服务器发。rn循环执行。rnrn大部分情况都很好,只是出现一个怪现象。rn没隔10分钟,就会出现收不到数据的情况。发现每隔10分钟,SOCKET会缓存几拍一起发送。rnrn我已经设置SOKET为NO_DELAY发送了,还是不行。rnrn各位大虾,给点意见吧。rnrn服务端建立程序如下:rn /* The WinSock DLL is acceptable. Proceed. */rn GROUP g = 0;rn //rn sServer = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_IP, NULL, g, 0);rn //sServer = WSASocket(AF_INET, SOCK_RAW, IPPROTO_RAW, NULL, 0, WSA_FLAG_OVERLAPPED);rnrn //创建套接字rn sockaddr_in sockAddr;rn rn memset(&sockAddr, 0, sizeof(sockaddr_in));rn sockAddr.sin_family = AF_INET;rn sockAddr.sin_port = htons(SerPort);rn sockAddr.sin_addr.S_un.S_addr = inet_addr(IPAddr);rn rn int ret = bind(sServer, (sockaddr*)(&sockAddr), sizeof(sockaddr_in));rnrn if (ret != 0)rn rn return CTEC_BINDERR;rn rn elsern rn DWORD dwBytesReturned = 0;rn BOOL bNewBehavior = TRUE; //ture 非阻塞 false 阻塞rn DWORD status;rn // disable new behavior usingrn // IOCTL: SIO_UDP_CONNRESETrn status = WSAIoctl(sServer, FIONBIO,rn &bNewBehavior, sizeof(bNewBehavior),rn NULL, 0, &dwBytesReturned,rn NULL, NULL);rnrn if (SOCKET_ERROR == status)rn rn DWORD dwErr = WSAGetLastError();rn if (WSAEWOULDBLOCK == dwErr)rn rn // nothing to dorn return 0;rn rn elsern rn return 0;rn rn rnrn int killnagle = 0;rn int result = setsockopt(sServer, IPPROTO_IP, TCP_NODELAY, (const char*)&killnagle, sizeof(int));rnrn if (result != 0)rn rn return 0;rn rnrn setsockopt(sServer,SOL_SOCKET,SO_SNDBUF,(const char*)&nSendBuf,sizeof(int));rn setsockopt(sServer,SOL_SOCKET,SO_RCVBUF,(const char*)&nRecvBuf,sizeof(int));rn rn listen(sServer, 1);rnrn客户端建立如下:rn GROUP g = 0;rn// sClient = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, g, 0);rn sClient = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_IP, NULL, g, 0);rnrn sockaddr_in dstAddr;rn dstAddr.sin_family = AF_INET;rn dstAddr.sin_addr.S_un.S_addr = inet_addr(sServerAddr);rn dstAddr.sin_port = htons(uSerPort);rnrn int ret = WSAConnect(sClient, (sockaddr*)(&dstAddr), sizeof(SOCKADDR), NULL, NULL,NULL, NULL );rnrn if (ret == 0)rn rn pClientRecvBuffer = new char[MAX_DATA_LEN];rn memset(pClientRecvBuffer, 0, MAX_DATA_LEN);rn rn DWORD dwBytesReturned = 0;rn BOOL bNewBehavior = TRUE; //ture Not blocking false blockingrn DWORD status;rn // disable new behavior usingrn // IOCTL: SIO_UDP_CONNRESETrn status = WSAIoctl(sClient, FIONBIO,rn &bNewBehavior, sizeof(bNewBehavior),rn NULL, 0, &dwBytesReturned,rn NULL, NULL);rnrn if (SOCKET_ERROR == status)rn rn DWORD dwErr = WSAGetLastError();rn if (WSAEWOULDBLOCK == dwErr)rn rn // nothing to dorn return 0;rn rn elsern rn return 0;rn rn rnrn int killnagle = 0;rn int result = setsockopt(sClient, IPPROTO_IP, TCP_NODELAY, (const char*)&killnagle, sizeof(int));rnrn if (result != 0)rn rn return 0;rn rnrn setsockopt(sClient,SOL_SOCKET,SO_SNDBUF,(const char*)&nSendBuf,sizeof(int));rn setsockopt(sClient,SOL_SOCKET,SO_RCVBUF,(const char*)&nRecvBuf,sizeof(int));
TCP/IP通讯源码
基于MFC的TCP/IP的socket源码编程。
TCP/IP通讯程序
Delphi编写的TCP/IP通讯练习程序
tcp/ip完成通讯
tcp/ip完成通讯 client server 完成信息互发
TCP/IP通讯测试软件
有关WSNetSvr.EXE和WSNetClt.EXE的一些应用信息: 1、WSNetSvr.EXE和WSNetClt.EXE分别为服务器端(Listen)和客户端(Connect)的二个部分; 2、WSNetSvr.EXE用于开发通讯程序时,在服务器端测试TCP/IP通讯连接以及测试数据的接收与发送情况。 3、WSNetClt.EXE用于开发通讯程序时,在客户端测试TCP/IP通讯连接以及测试数据的接收与发送情况。 4、运行的操作系统为Windows 95/98/2000,以及Windows NT 3.51/4.0/5.0; 5、操作系统需要安装TCP/IP协议; 6、WSNetSvr.EXE和WSNetClt.EXE可以在同一台计算机上使用; 7、WSNetSvr.EXE作为Server端可以同时接收多个连接,具体数目与计算机内存相关,内存越大, 可以连接的数目也越多; 9、WSNetSvr.EXE和WSNetClt.EXE可以分开分别使用,以便与自己测试开发的通讯程序相对应,配合以及 检测自己的通讯程序; 10、要求首先启动Server端的程序,再启动Client端的程序;启动WSNetSvr.EXE或WSNetClt.EXE后,需要 初始化网络,WSNetSvr.EXE需要输入端口号,WSNetClt.EXE需要输入Server端的IP地址(域名也可以) 和端口号;
tcp/ip的通讯程序
比较详细的介绍了编写tcp/ip的通讯程序,重点讲解了各个组件的属性,方法,非常适用于初学者
Tcp/Ip通讯程序
本程序示例二台计算机如何通过Tcp/Ip方式进行点对点通讯。
TCP/IP多线程通讯
以前为公司写的一套通讯软件.功能完善,使用套接字加多线程完成
TCP/IP通讯模块
好用的TCP/IP通讯库,通讯逻辑已经封装好,只需要绑定事件来获取通信内容,然后添加自己的处理逻辑
STM32 tcp/ip通讯
详细的代码,每一步都有中文解释。通过编译,无错误,KEIL.
关于tcp/ip通讯
请教如何在dos下将数据以tcp/ip协议传送出去?(将数据打包成tcp/ip的数据包)其实还有大问题就是如何在dos下进行tcp/ip通讯,这个问题可能会被高手笑,可是没办法。请各位帮帮忙!rn 提供一些有例程的入门教材,我也知道要在2天时间内弄懂是不可能的,但rn也不能什么都不知道吧!应用级的tcp/ip大家都会,可是底层小弟就不知了!rn所以请各位帮帮忙呀!
TCP/IP通讯
[code=csharp] protected void Button3_Click(object sender, EventArgs e)rn rn TcpClient tcp = new TcpClient();rn tryrn rnrn tcp.Connect(WwendPoint1);rn rn catch (Exception ex)rn rn Response.Write(ex);rn rnrn if (tcp.Connected)rn rn NetworkStream streamToServer = tcp.GetStream();rn streamToServer.Write(WeightQuest, 0, WeightQuest.Length);rn byte[] weightGet = new byte[16];rn streamToServer.Read(weightGet, 0, weightGet.Length);rn float weight = DoWeightData(weightGet);rn TextBox1.Text = weight.ToString();rn rn tcp.Close();rn[/code]rnrn用这段代码一到这段[code=csharp]streamToServer.Read(weightGet, 0, weightGet.Length);rn[/code]就反应不过来。后来我发现streamToServer的DataAvailable = false。为什么我已经写进去了却读不出来值呢?后来我用telnet也是连接该IP地址的这个端口,与它会话,就可以取到正常的。[img=https://img-bbs.csdn.net/upload/201502/03/1422948102_219449.png][/img]
TCP/IP异步聊天C#(已封装)
基于TCP/IP异步聊天程序。。。域名解析的是本机地址 所以客户端和服务端都在一个机器上运行调试
用C#编写的TCP/IP异步的聊天程序
用C#编写的TCP/IP异步的聊天程序,有兴趣的可以看下
Socket编程(异步通讯)(Tcp,Udp)
主要展示了Socket的Tcp\Udp两种协议下的基本通讯方式,属于同步通讯。至于一个服务器对应多个客户端,或者对应多个请求,我们采用的是多线程的方式来解决此问题。我们将有更好的方式去实现它:Socket在Tcp\Udp两种协议下的异步通讯方式.
西门子S7-200SMART TCP/IP 通讯连接库(C#)
电脑通过 Socket 协议与 西门子S7-200SMART PCL 通讯(包括读取和写入)的动态连接库
有关TCP异步通讯问题
关于TCP异步通讯中,我一直有几个问题没搞明白rn1.TCP异步通讯到底有什么作用???哪位大神能给我举个例子来说说不Orzrn2.关于下面这段代码中WaitOne这个东西(阻止当前线程),这样写了以后那不是和TCP同步通讯是一样的效果了,都是要阻塞当前线程,那我干嘛还这么麻烦的写一个异步程序,直接写一个同步的多好啊。(这个程序是一本书上的TCP异步的例子)rn[code=csharp] private void but_connect_Click(object sender, EventArgs e)rn rn tryrn rn client = new TcpClient(AddressFamily.InterNetwork);rn IPAddress ipadd = IPAddress.Parse(txt_hostname.Text.ToString());rnrn AsyncCallback requestCallBack = new AsyncCallback(RequestCallBack);rn allDone.Reset();rnrn client.BeginConnect(ipadd, 3000, requestCallBack, client);rnrn //public object Invoke(Delegate method, params object[] args);调用callbackrn lb_state.Invoke(setlistboxcallback, string.Format("本机终结点:0", client.Client.LocalEndPoint));rn lb_state.Invoke(setlistboxcallback, "开始与服务器连接...");rn allDone.WaitOne();rn rn catch (Exception ee)rn rn lb_state.Invoke(setlistboxcallback, string.Format("错误:0", ee.Message));rn rn finallyrn rn rnrn [/code]rn3.解决TCP异步这个问题,直接开启多线程不就好了吗,干嘛还要弄异步这个东西,多麻烦啊??rn
TCP的同步与异步通讯问题
想问下大家,如何做到同步与异步通讯可以切换进行?rnrn我的需求是这样的在同一个连接中我发送某个命令,需要同步的方式读回服务器给返回的状态信息.rn然后根据这个状态在启动异步通讯与服务器交换数据.rnrn但是我一旦设置了readyRead()信号对应的槽后,我的同步读 数据的操作(waitForReadyRead)就不能读到数据了,每次有数据都跳到了我的槽函数中了.rnrn我现在想问问有没有办法我想同步读时就不要异步的槽函数相应,不需要同步时又能切换到异步上去?rnrn谢谢各位
异步Socket的Tcp通讯服务器
异步Socket的Tcp通讯服务器主要用于管理连接上的客户端及其与客户端进行通信。
c#两台主机通讯(TCP/IP)判断
谁能帮帮我,我要做个局域网一台主机与另一台目的主机的通讯(目的主机开放了端口号)判断并做出相应的提示(通讯正常或中断),谢谢!
C#实现串口通讯和TCP/IP通讯的示例程序
包含一个与PLC进行网络通讯和与外部设备进行串口通讯的程序
tcp/ip通讯,使用c#进行socket编程
tcp/ip通讯,使用c#进行socket编程
TCP通讯修改.rar
这是用WINAPI创建的通讯!喜欢DELPHI的朋友可以下载研究下!!!!
C# 异步通讯 UDP
using System;rnusing System.Collections.Generic;rnusing System.Linq;rnusing System.Text;rnusing System.Net;rnusing System.Net.Sockets;rnusing System.Threading;rnrnnamespace UdpSenderrnrn public class UdpPostedrn rn public void SendCallback(IAsyncResult iar)rn rn //UdpClient uc = (UdpClient)iar.AsyncState;rn Console.WriteLine("numbers of bytes send and time is 0", DateTime.Now.ToString());rn rnrn public void SendMessageUdp(IPAddress ipa, int port, string message)rn rn UdpClient uc = new UdpClient();rn IPEndPoint iep = new IPEndPoint(ipa, port);rnrn byte[] sendBytes = Encoding.ASCII.GetBytes(message);rn //uc.Ttl = 1;rn uc.BeginSend(sendBytes, sendBytes.Length, iep, new AsyncCallback(SendCallback), uc);rn rnrn ////定义UDP的发送端rn //public static UdpClient uSenderSlot;rnrn ////定义所要发送的IPrn //public static IPAddress ipa;rnrn ////定义所要发送的IPErn //public static IPEndPoint ipe;rn rn ////定义所要发送的范围和端口号rn //public UdpPosted(byte [] ipbs, int iport)rn //rn // ipa = new IPAddress(ipbs);rn // ipe = new IPEndPoint(ipa, iport);rnrn // uSenderSlot = new UdpClient(ipe);rn //rnrn //public void SendCallback(IAsyncResult iar)rn //rn // UdpClient u = (UdpClient)iar.AsyncState;rn // Console.WriteLine("The UdpSender send 0.",u.EndSend(iar));rn //rnrn //public void PostMsgToTarget(string msg)rn //rn // Byte[] sendBytes = Encoding.ASCII.GetBytes(msg);rn // uSenderSlot.BeginSend(sendBytes, sendBytes.Length, ipe, new AsyncCallback(SendCallback), uSenderSlot);rn //rnrn rnrn class Programrn rn static void Main(string[] args)rn rn byte [] target = new byte[4]255,255,255,255;rnrn UdpPosted udpPost = new UdpPosted();rnrn while (true)rn rn udpPost.SendMessageUdp(new IPAddress(target), 12000, DateTime.Now.ToString());rn Thread.Sleep(1);rn rn rn rnrnrnrnrnrnusing System;rnusing System.Collections.Generic;rnusing System.Linq;rnusing System.Text;rnusing System.Net;rnusing System.Net.Sockets;rnusing System.Threading;rnrnnamespace UdpListenerrnrn public class MsgReceivedArgs : EventArgsrn rn private readonly string recvMsg;rnrn public MsgReceivedArgs(string target)rn rn recvMsg = target;rn rnrn public string RecvMsgrn rn get return recvMsg; rn rn rnrn public class UdpReceivedrn rn //定义UDP的接收端rn public static UdpClient uReceiverSlot;rnrn //定义IPEndPoint端rn public static IPEndPoint ipEp;rnrn //订阅者必须实现的委托rn public delegate void MsgReceiverHandler(object sender, MsgReceivedArgs receiveMsg);rnrn //控制者对于委托的访问rn public event MsgReceiverHandler OnMsgReceived;rnrn //生成一个对应端口的UDPClient,监听任意地址所发来的消息。rn public UdpReceived(int port)rn rn ipEp = new IPEndPoint(IPAddress.Any, port);rn uReceiverSlot = new UdpClient(ipEp);rn rnrn //UDPClient的异步接收rn public void StartReceive()rn rn uReceiverSlot.BeginReceive(new AsyncCallback(ReceiveCallback), ipEp);rn Thread.Sleep(System.Threading.Timeout.Infinite);rn rnrn //UDPClient异步接收到指令后的函数rn public void ReceiveCallback(IAsyncResult iar)rn rn IPEndPoint ipe = (IPEndPoint)ipEp;rn Byte[] receiveBytes = uReceiverSlot.EndReceive(iar, ref ipe);rnrn string receiveMessage = Encoding.ASCII.GetString(receiveBytes);rnrn //创建MsgReceivedArgs 对象 传给订阅者rn if (receiveBytes.Length > 0)rn rn MsgReceivedArgs receiveInformation = new MsgReceivedArgs(receiveMessage);rnrn if (OnMsgReceived != null)rn rn OnMsgReceived(this, receiveInformation);rn rn rnrn //重新进行接收rn uReceiverSlot.BeginReceive(new AsyncCallback(ReceiveCallback), ipEp);rn rnrn rnrn public class Testerrn rn public void Subscribe(UdpReceived theUdp)rn rn theUdp.OnMsgReceived += new UdpReceived.MsgReceiverHandler(theUdp_OnMsgReceived);rn rnrn void theUdp_OnMsgReceived(object sender, MsgReceivedArgs receiveMsg)rn rn Console.WriteLine("The udpClient received a 0.", receiveMsg.RecvMsg);rn rn rnrn class Programrn rn static void Main(string[] args)rn rn UdpReceived udpR = new UdpReceived(12000);rn Tester test = new Tester();rn test.Subscribe(udpR);rnrn udpR.StartReceive();rn rn rnrnrnrn
c# UDP异步通讯
采用socket类编写的一个简单的给自己发送UDP消息的窗口程序。采用异步方式,程序中注释部分代码为采用同步方式。