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. 【noiOJ】p8206

    02:二分法求函数的零点 查看 提交 统计 提问 总时间限制:  1000ms 内存限制:  65536kB 描述 有函数: f(x) = x5 - 15 * x4+ 85 * x3- 225 * x ...

  2. 构建json数据post到接口的若干条规则

    接受数据接口: public ActionResult PostDownloadLog(PostDownloadLog postDownloadLogs) PostDownLoadLogL类 publ ...

  3. Node.js的函数返回值

    先看一段代码: function select(sqlscript){     var result = "";     sql.connect(config, function( ...

  4. 【Go语言】错误与异常处理机制

    ①error接口 Go语言中的error类型实际上是抽象了Error()方法的error接口 type error interface { Error() string } Go语言使用该接口进行标准 ...

  5. Odoo 仓库扫码打包方案

        Odoo仓库扫码的设计,前提是操作人在PC上先做好分拣单,然后根据打印出来的分拣单去仓库进行扫码打包,默认的情况下,分拣在被确认的时候会自动保留库位中已经存在的库存(已经分配批次\序列号),而 ...

  6. 拿到添加对象的id号方法

    以前Hibernate添加对象,想拿到id号的时候都是根据id排序拿到第一条 ,才知道 这样也可以 /**         * @Description: 添加一个角色信息        * @ret ...

  7. 服务器由于redis未授权漏洞被攻击

    昨天阿里云拦截到了一次异常登陆,改了密码后就没有管他, 今天阿里云给我发消息说我的服务器可能被黑客利用,存在恶意发包行为....... 不过我不打算只是单纯的重置系统,经过一系列的查找原因后,发现被攻 ...

  8. thinkphp多模板布局设置!!

    首先开启模板布局要在配置文件添加: 'LAYOUT_ON'=>true, 'LAYOUT_NAME'=>'layout', 如果需要设置多个布局模板,就要先关闭上面的LAYOUT_ON,也 ...

  9. JS 心得总结

    1.浏览器关闭事件监听(http://pengjianbo1.iteye.com/blog/507569,http://bbs.csdn.net/topics/360152711) <!DOCT ...

  10. hdu Code Lock

    题意是说有N个字母组成的密码锁, 如[wersdfj],   每一位上的字母可以转动, w可转动变成x, z变成a.但是题目规定, 只能同时转动某个区间上的所有字母, 如[1,3], 那么第1到第3个 ...