📄 simpleudp.cs
字号:
using System;
using System.Collections.Generic;
using System.Text;
using GPCore.NetworkProtocols;
using System.Net;
using System.Net.Sockets;
using GPCore;
namespace GPPlugins
{
/// <summary>
/// A simple UDPImplementation of the NetworkProtocol class.
/// </summary>
[GPCore.Plugin("UDP", "1.0", "James Regan", "Gibphone", "A network protocol without error checking")]
public class SimpleUdp : NetworkProtocol
{
/// <summary>
/// Call this to send data to the given IPaddress.
/// </summary>
/// <param name="a"></param>
/// <param name="To"></param>
public override void SendData(byte[] a, System.Net.IPAddress To)
{
try
{
client.BeginSend(a, a.Length, new IPEndPoint(To, port), delegate(IAsyncResult result)
{
try
{
client.EndSend(result);
}
catch (SocketException)
{
}
},null);
}
catch (Exception) { }
}
UdpClient client;
/// <summary>
/// Call this to initialize SimpleUdp.
/// </summary>
/// <param name="port"></param>
public override void Initialize(int port)
{
base.Initialize(port);
client = new UdpClient(port);
client.BeginReceive(new AsyncCallback(UdpDataReceived), null);
}
protected void UdpDataReceived(IAsyncResult result)
{
IPEndPoint sender = new IPEndPoint(1, 0);
if (client.Client == null) return;
try
{
byte[] a = client.EndReceive(result, ref sender);
DataReceived(a, sender.Address);
client.BeginReceive(new AsyncCallback(UdpDataReceived), null);
}
catch (Exception)
{ }
}
public override event NetworkDelegate DataReceived;
public override byte[] PauseForData(IPAddress From, int Size)
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp);
byte[] a = new byte[Size];
EndPoint end = new IPEndPoint(From, port);
try
{
int i = sock.ReceiveFrom(a, 0, Size, SocketFlags.None, ref end);
if (i > 0)
{
return a;
}
}
catch (SocketException e)
{
onError(this, "onError", new ExceptionEventArgs(new Exception(Enum.GetName(typeof(SocketError), e.SocketErrorCode), e)));
}
return new byte[0];
}
public override void Dispose()
{
this.client.Close();
}
public override event NotifyCore onError;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -