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. 深入浅出-Android系统移植与平台开发(一)- Android4.0系统的下载与编译

    作者:唐老师,华清远见嵌入式学院讲师. 一.Android4.0系统的下载与编译 Android系统的下载与编译,Google的官方网站上已经给出了详细的说明,请参照Android的官方网址: htt ...

  2. Linux多线程实例练习 - pthread_exit() 与 pthread_join()

    Linux多线程实例练习 - pthread_exit 与 pthread_join pthread_exit():终止当前线程 void pthread_exit(void* retval); pt ...

  3. Listener监听器使用小案例

    这里介绍的就是一个客户流失监听器案例 新建一个监听器实现ServletContextListener接口 覆写contextDestroyed和contextInitialized 方法 packag ...

  4. [转载]CRect::DeflateRect

    1基本内容 void DeflateRect(int x,int y); void DeflateRect(SIZE size); void DeflateRect(LPCRECT lpRect); ...

  5. zk回车事件

    private Textbox testTextB; testTextB.addEventListener(Events.ON_OK, new EventListener<Event>() ...

  6. 允许浏览器跨域访问web服务端的解决方案

    今天和同事探讨了前后端如何真正实现隔离开发的问题,如果前端单独作为服务发布,势必会涉及到无法直接调用后端的接口的问题,因为浏览器是不允许跨域提交请求的. 所谓跨域访问,就是在浏览器窗口,和某个服务端通 ...

  7. zju(5)LED控制实验

    1.实验目的 1.学习和掌握如何将一个驱动程序添加到Kconfig,编译到内核. 二.实验内容 1.编写EduKit-IV试验箱Linux操作系统下LED灯的驱动: 2.编写EduKit-IV试验箱L ...

  8. tomcat启动后,在普通java类中获取spring管理的bean和ServletContext,(经过验证,可以取到)

    //从spring容易中获取bean public static Object getBean(String beanName){ ApplicationContext context = Conte ...

  9. PHP如何通过SQL语句将数据写入MySQL数据库呢?

    1,php和MySQL建立连接关系 2,打开 3,接受页面数据,PHP录入到指定的表中 1.2两步可直接使用一个数据库链接文件即可:conn.php <?phpmysql_connect(&qu ...

  10. IOS彩票第二天设置界面(1)

    ****跳转到设置界面 - (IBAction)setting:(id)sender { // 创建设置口控制器 ILSettingTableViewController *settingVc = [ ...