C# UDP 连接通信 简单示例
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 连接通信 简单示例的更多相关文章
- UDP通讯模型简单示例
1. UDP通讯模型 2. 服务器端 ① 创建一个socket,用函数socket() ② 绑定IP地址.端口等信息到socket上,用函数bind() ③ 循环接收数据,用函数recvfrom() ...
- JAVA使用jdbc连接MYSQL简单示例
以下展示的为JAVA使用jdbc连接MYSQL简单示例: import java.sql.DriverManager; import java.sql.ResultSet; import java.s ...
- redis -- python操作连接redis简单示例
1.先安装 redis,pyredis sudo pip install redis sudo pip install python-redis 2.示例: importredis >>& ...
- SQL左连接、右连接和内连接的简单示例
left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录: right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录: inner join(等值连接 ...
- 安卓中使用HttpURLConnection连接网络简单示例 --Android网络编程
MainActivity.java: package thonlon.example.cn.httpurlconnectionpro; import android.os.Bundle;import ...
- 网络编程4 网络编程之FTP上传简单示例&socketserver介绍&验证合法性连接
今日大纲: 1.FTP上传简单示例(详细代码) 2.socketserver简单示例&源码介绍 3.验证合法性连接//[秘钥加密(urandom,sendall)(注意:中文的!不能用)] 内 ...
- UDP通信简单 小结
Android手机版和电脑版 效果图: 通过WiFi局域网 电脑和手机连接通信. 电脑版本和手机版本使用了相同的消息发送头协议, 可以相互接收消息. 若有做的不好的地方还希望大家指导一下. 1. 手机 ...
- TODO:Golang UDP连接简单测试慎用Deadline
TODO:Golang UDP连接简单测试慎用Deadline UDP 是User Datagram Protocol的简称, 中文名是用户数据报协议,是OSI(Open System Interco ...
- 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 ...
随机推荐
- URAL 1501. Sense of Beauty(记忆化搜索)
题目链接 本来暴力写个TLE了,加上记忆化就A了. #include <cstring> #include <cstdio> #include <string> # ...
- Java_过滤字符串中非汉子的内容
/** * 去除“第”之前的所有非汉字内容 */ private String clearNotChinese(String buff){ String tmpString =buff.replace ...
- ELK_elk+redis 搭建日志分析平台
这个是最新的elk+redis搭建日志分析平台,今年时间是2015年9月11日. Elk分别为 elasticsearch,logstash, kibana 官网为:https://www.elast ...
- DataTable在内存中的使用
DataTable表示一个与内存有关的数据表,可以使用工具栏里面的控件拖放来创建和使用,也可以在编写程序过程中根据需要独立创建和使用,最常见的情况是作为DataSet的成员使用,在这种情况下就需要用在 ...
- Java Web include指令和动作的区别
- 示例Oracle 10.2.0.1.0升级到10.2.0.4.0一例
1.查看当前系统版本 [oracle@std Disk1]$ sqlplus '/as sysdba' SQL*Plus: Release - Production on Thu Jan :: Cop ...
- java中内部类使用小结
内部类是指在一个外部类中再定义一个类,类名不需要和文件名相同 内部类可以是静态的,类的修饰符可以是private,default,protect,public修饰 ,而外部类只能是public 和 d ...
- 除了白名单外的IP每秒最多处理 8 个请求 limit_conn_zone
防止黑客知道你的源服务器真实IP进行并发攻击,通常只需要保护动态文件请求,�php. 添加文件 nginx/conf/limit/whiteip.conf 里面是你要忽略限制的 白名单 IP地址,通常 ...
- jsp\struts1.2\struts2 中文件上传(转)
jsp\struts1.2\struts2 中文件上传 a.在jsp中简单利用Commons-fileupload组件实现 b.在struts1.2中实现c.在sturts2中实现现在把Code与大家 ...
- php实现数字格式化,数字每三位加逗号的功能函数
原地址:http://www.jb51.net/article/73781.htm php实现数字格式化,数字每三位加逗号的功能函数,具体代码如下: ? 1 2 3 4 5 6 7 8 9 10 11 ...