Udp.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets; namespace udp
{
public delegate void UdpEventHandler(object sender, UdpEventArgs e); public abstract class Udp : IUdp
{
public event UdpEventHandler Received; private int _port;
private string _ip;
public bool IsListening { get; private set; }
private Socket _sck; public Socket UdpSocket
{
get { return _sck; }
}
public string Ip
{
get { return _ip; }
set { _ip = value; }
}
public int Port
{
get { return _port; }
set
{
if (value < )
value = ;
if (value > )
value = ;
_port = value;
}
} public Udp()
{
_sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_sck.ReceiveBufferSize = UInt16.MaxValue * ;
//log
System.Diagnostics.Trace.Listeners.Clear();
System.Diagnostics.Trace.AutoFlush = true;
System.Diagnostics.Trace.Listeners.Add(new System.Diagnostics.TextWriterTraceListener("log.txt"));
} public void Listening()
{
IPAddress ip = IPAddress.Any;
try
{
if (this._ip != null)
if (!IPAddress.TryParse(this._ip, out ip))
throw new ArgumentException("IP地址错误", "Ip");
_sck.Bind(new IPEndPoint(ip, this._port)); UdpState state = new UdpState();
state.Socket = _sck;
state.Remote = new IPEndPoint(IPAddress.Any, );
_sck.BeginReceiveFrom(state.Buffer, , state.Buffer.Length, SocketFlags.None, ref state.Remote, new AsyncCallback(EndReceiveFrom), state);
IsListening = true;
}
catch (ArgumentException ex)
{
IsListening = false;
System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "\t" + ex.Message);
throw ex;
}
catch (Exception ex)
{
IsListening = false;
System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "\t" + ex.Message);
throw ex;
}
}
private void EndReceiveFrom(IAsyncResult ir)
{
if (IsListening)
{
UdpState state = ir.AsyncState as UdpState;
try
{
if (ir.IsCompleted)
{
int length = state.Socket.EndReceiveFrom(ir, ref state.Remote);
byte[] btReceived = new byte[length];
Buffer.BlockCopy(state.Buffer, , btReceived, , length);
OnReceived(new UdpEventArgs(btReceived, state.Remote));
}
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "\t" + ex.Message+ex.Source);
}
finally
{
state.Socket.BeginReceiveFrom(state.Buffer, , state.Buffer.Length, SocketFlags.None, ref state.Remote, new AsyncCallback(EndReceiveFrom), state);
}
}
} private void OnReceived(UdpEventArgs e)
{
if (this.Received != null)
{
Received(this, e);
}
} public void Send(byte[] bt, EndPoint ep)
{
if (_sck == null) return;
try
{
this._sck.SendTo(bt, ep);
}
catch (SocketException ex)
{
System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "\t" + ex.Message);
throw ex;
}
} public void Dispose()
{
if (_sck == null) return; using (_sck) ;
//this.IsListening = false;
//this._sck.Blocking = false;
//this._sck.Shutdown(SocketShutdown.Both);
//this._sck.Close();
//this._sck = null;
} }
}

IUdp.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net; namespace udp
{
public interface IUdp : IDisposable
{
event UdpEventHandler Received; void Send(byte[] bt, EndPoint ep); Socket UdpSocket { get; }
}
}

UdpEventArgs.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net; namespace udp
{
public class UdpEventArgs : EventArgs
{
private EndPoint _remote; private byte[] _rec; public byte[] Received
{
get { return _rec; }
}
public EndPoint Remote
{
get { return _remote; }
} public UdpEventArgs(byte[] data, EndPoint remote)
{
this._remote = remote;
this._rec = data;
}
}
}

UdpState.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets; namespace udp
{
internal class UdpState
{
public byte[] Buffer;
public EndPoint Remote;
public Socket Socket; public UdpState()
{
Buffer = new byte[];
}
}
}

Client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using udp;
namespace client
{
class Program
{
private const string _serverIp = "127.0.0.1";
private const int _serverPort = ; static void Main(string[] args)
{
Client client = new Client();
client.ep = new IPEndPoint(IPAddress.Parse(_serverIp), _serverPort);
client.Listening();
client.Received += new UdpEventHandler(client_Received);
while (true)
{
string tmp = Console.ReadLine();
for (int i = ; i < ; i++)
{
byte[] bt = Encoding.Default.GetBytes(tmp + i);
System.Threading.Thread t = new System.Threading.Thread(() =>
{
client.Send(bt, client.ep);
});
t.Start();
}
client.Dispose();
}
} static void client_Received(object sender, UdpEventArgs e)
{
IPEndPoint ep = e.Remote as IPEndPoint;
string tmpReceived = Encoding.Default.GetString(e.Received);
Console.WriteLine(ep.Address.ToString() + ":" + ep.Port + "--> " + tmpReceived);
}
} public class Client : Udp
{
public EndPoint ep;
public Client()
{ }
}
}

Server

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Net.Sockets;
using System.Net;
using udp; namespace server
{
class Program
{
static Server server = new Server();
static void Main(string[] args)
{
server.Port = ;
server.Listening();
if (server.IsListening)
{
server.Received += new UdpEventHandler(server_Received);
}
Console.ReadKey();
} static void server_Received(object sender, UdpEventArgs e)
{
IPEndPoint ep = e.Remote as IPEndPoint;
string tmpReceived = Encoding.Default.GetString(e.Received);
Console.WriteLine(ep.Address.ToString() + ":" + ep.Port + "--> " + tmpReceived);
///自动回复
server.Send(Encoding.Default.GetBytes("服务器已收到数据:'" + tmpReceived + "',来自:‘" + ep.Address.ToString() + ":" + ep.Port + "’"), ep);
} }
public class Server : Udp
{
private EndPoint ep;
public Server()
{
}
}
}

源码文件

C# UDP 连接通信 简单示例的更多相关文章

  1. UDP通讯模型简单示例

    1. UDP通讯模型 2. 服务器端 ① 创建一个socket,用函数socket() ② 绑定IP地址.端口等信息到socket上,用函数bind() ③ 循环接收数据,用函数recvfrom() ...

  2. JAVA使用jdbc连接MYSQL简单示例

    以下展示的为JAVA使用jdbc连接MYSQL简单示例: import java.sql.DriverManager; import java.sql.ResultSet; import java.s ...

  3. redis -- python操作连接redis简单示例

    1.先安装 redis,pyredis sudo pip install redis sudo pip install python-redis 2.示例: importredis >>& ...

  4. SQL左连接、右连接和内连接的简单示例

    left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录: right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录: inner join(等值连接 ...

  5. 安卓中使用HttpURLConnection连接网络简单示例 --Android网络编程

    MainActivity.java: package thonlon.example.cn.httpurlconnectionpro; import android.os.Bundle;import ...

  6. 网络编程4 网络编程之FTP上传简单示例&socketserver介绍&验证合法性连接

    今日大纲: 1.FTP上传简单示例(详细代码) 2.socketserver简单示例&源码介绍 3.验证合法性连接//[秘钥加密(urandom,sendall)(注意:中文的!不能用)] 内 ...

  7. UDP通信简单 小结

    Android手机版和电脑版 效果图: 通过WiFi局域网 电脑和手机连接通信. 电脑版本和手机版本使用了相同的消息发送头协议, 可以相互接收消息. 若有做的不好的地方还希望大家指导一下. 1. 手机 ...

  8. TODO:Golang UDP连接简单测试慎用Deadline

    TODO:Golang UDP连接简单测试慎用Deadline UDP 是User Datagram Protocol的简称, 中文名是用户数据报协议,是OSI(Open System Interco ...

  9. SignalR代理对象异常:Uncaught TypeError: Cannot read property 'client' of undefined 推出的结论 SignalR 简单示例 通过三个DEMO学会SignalR的三种实现方式 SignalR推送框架两个项目永久连接通讯使用 SignalR 集线器简单实例2 用SignalR创建实时永久长连接异步网络应用程序

    SignalR代理对象异常:Uncaught TypeError: Cannot read property 'client' of undefined 推出的结论   异常汇总:http://www ...

随机推荐

  1. PHP递归小例子

    $news = M('productbase'); function digui($idd){ $child=M('navclass')->where('f_id='.$idd)->sel ...

  2. PHP.ini文件读取不到

    Configuration File (php.ini) Path /usr/local/php/lib Loaded Configuration File (none) Linux 把 dtruss ...

  3. jquery .post .get中文参数乱码解决方法详解

    jquery默认的编码为utf-8,做项目时有时处于项目需要用到ajax提交中文参数,乱码问题就很头疼了,折腾了许久终于弄出来了.为了便于传输,我们首先将需要用到的参数用javascript自带的函数 ...

  4. power 做表

    drop table "USER" cascade constraints; /*================================================= ...

  5. web前端开发CSS命名规范参考

    做为一个web前端工程师,每天接触HTML.css就像吃饭一样,但是作为一名合作.优秀的web前端工程师,对DIV+CSS命名还是有一定的规范的,本文整理了一份web前端开发中DIV+CSS各种命名规 ...

  6. IE中的CSS3不完全兼容方案

    摘要: Internet Explorer,其本身也是足够强大的.IE特有的技术可以很好的实现一些CSS3的效果. 到Internet Explorer 8为止,IE系列是不支持CSS3的.在IE中要 ...

  7. javascript平时小例子①(移动的小div)

    css样式: #box{ width: 300px; height: 300px; background: deepskyblue; position: absolute; margin-right: ...

  8. Oracle数据库表复制语句

    Insert是T-sql中常用语句,Insert INTO table(field1,field2,...) values(value1,value2,...)这种形式的在应用程序开发中必不可少.但我 ...

  9. Hibernate SQLQuery简单实用,做链接查询

    工单里面可能有0个告警,一个或多个告警,当工单中没有告警的时候也需要将工单显示出来,所以就需要使用工单和告警的做链接查询,下面是具体实例 表: CREATE TABLE `alarm` ( `id` ...

  10. SpringMVC表单标签简介

    在使用SpringMVC的时候我们可以使用Spring封装的一系列表单标签,这些标签都可以访问到ModelMap中的内容.下面将对这些标签一一介绍. 在正式介绍SpringMVC的表单标签之前,我们需 ...