rudp可靠保障得udp传输
源代码在线查看: serverform.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;
using Helper.Net.RUDP;
using Helper.Net.UDT;
namespace Test.Application
{
public partial class ServerForm : Form
{
#region Variables
private Thread thread;
//---- Sockets
private RUDPSocket rudpSocket;
private RUDPSocket newRUDPSocket;
private Socket tcpSocket;
private Socket newTCPSocket;
private UDTSocket udtSocket;
private UDTSocket newUDTSocket;
private byte[] buffer = new byte[32 * 1024];
//---- Rates
private double _currentRate = -1;
long CurrentTotalBytes;
private double _rate = -1;
long TotalBytes;
Stopwatch _globalStopwatch = new Stopwatch();
Stopwatch _currentStopwatch = new Stopwatch();
int _currentRateInterval = 1000;
//---- Graph
private Test.Helper.Windows.LineHandle _perfLineAverage;
private Test.Helper.Windows.LineHandle _perfLineCurrent;
#endregion
#region Constructor
public ServerForm()
{
InitializeComponent();
txtIPAddress.Text = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();
_perfLineAverage = performanceGraph.AddLine("AVERAGE", Color.White);
_perfLineCurrent = performanceGraph.AddLine("CURRENT", Color.Red);
}
#endregion
#region Events...
private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
thread = new Thread(new ThreadStart(StartBenchmark));
thread.Start();
// Data display refresh
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick_Data);
timer.Start();
// Performance graph refresh
timer = new System.Windows.Forms.Timer();
timer.Interval = 50;
timer.Tick += new EventHandler(timer_Tick_Graph);
timer.Start();
}
void timer_Tick_Data(object sender, EventArgs e)
{
txtRate.Text = ((int)_rate).ToString() + " KBytes/seconds";
txtCurrentRate.Text = ((int)_currentRate).ToString() + " KBytes/seconds";
txtTotalBytes.Text = "" + (TotalBytes / 1024);
if (!_globalStopwatch.IsRunning)
txtSeconds.Text = "0";
else
txtSeconds.Text = "" + _globalStopwatch.ElapsedMilliseconds / 1000;
}
void timer_Tick_Graph(object sender, EventArgs e)
{
if (_rate > -1)
performanceGraph.Push((int)_rate, "AVERAGE");
if (_currentRate > -1)
performanceGraph.Push((int)_currentRate, "CURRENT");
performanceGraph.UpdateGraph();
}
#endregion
#region StartBenchmark
private void StartBenchmark()
{
//---- 1 Accept
if (rbRUDP.Checked)
{
rudpSocket = new RUDPSocket();
rudpSocket.Bind(new IPEndPoint(IPAddress.Parse(txtIPAddress.Text), Int32.Parse(txtIPPort.Text)));
rudpSocket.BeginAccept(new AsyncCallback(OnAccept_RUDP), null);
}
else if (rbUDT.Checked)
{
udtSocket = new UDTSocket(AddressFamily.InterNetwork);
udtSocket.Bind(new IPEndPoint(IPAddress.Parse(txtIPAddress.Text), Int32.Parse(txtIPPort.Text)));
udtSocket.Listen(100);
udtSocket.BeginAccept(new AsyncCallback(OnAccept_UDT), null);
}
else
{
tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
tcpSocket.Bind(new IPEndPoint(IPAddress.Parse(txtIPAddress.Text), Int32.Parse(txtIPPort.Text)));
tcpSocket.Listen(100);
tcpSocket.BeginAccept(new AsyncCallback(OnAccept_TCP), null);
}
}
#endregion
#region OnAccept_RUDP
internal void OnAccept_RUDP(IAsyncResult result)
{
//---- Get the socket
newRUDPSocket = rudpSocket.EndAccept(result);
_globalStopwatch.Stop();
_currentStopwatch.Stop();
_globalStopwatch.Start();
_currentStopwatch.Start();
//---- Lesson for accept
rudpSocket.BeginAccept(new AsyncCallback(OnAccept_RUDP), null);
//---- Start receiving
newRUDPSocket.BeginReceive(new AsyncCallback(OnReceive_RUDP), Environment.TickCount);
}
#endregion
#region OnAccept_TCP
internal void OnAccept_TCP(IAsyncResult result)
{
//---- Get the socket
newTCPSocket = tcpSocket.EndAccept(result);
_globalStopwatch.Stop();
_currentStopwatch.Stop();
_globalStopwatch.Start();
_currentStopwatch.Start();
//---- Lesson for accept
tcpSocket.BeginAccept(new AsyncCallback(OnAccept_TCP), null);
//---- Start receiving
newTCPSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive_TCP), Environment.TickCount);
}
#endregion
#region OnAccept_UDT
internal void OnAccept_UDT(IAsyncResult result)
{
//---- Get the socket
newUDTSocket = udtSocket.EndAccept(result);
_globalStopwatch.Stop();
_currentStopwatch.Stop();
_globalStopwatch.Start();
_currentStopwatch.Start();
//---- Lesson for accept
udtSocket.BeginAccept(new AsyncCallback(OnAccept_UDT), null);
//---- Start receiving
newUDTSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive_UDT), Environment.TickCount);
}
#endregion
#region OnReceive_RUDP
internal void OnReceive_RUDP(IAsyncResult result)
{
if (!newRUDPSocket.Connected)
{
OnTransportDisconnected_RUDP();
return;
}
//---- Process the received bytes
try
{
byte[] bytes = newRUDPSocket.EndReceive(result);
int length = bytes.Length;
//---- End of connection
if (bytes == null)
{
// Connection closed by peer
OnTransportDisconnected_RUDP();
return;
}
//---- Current rate
double seconds;
int now = Environment.TickCount;
CurrentTotalBytes += length;
if (_currentStopwatch.ElapsedMilliseconds > _currentRateInterval)
{
seconds = ((double)_currentStopwatch.ElapsedMilliseconds) / 1000;
_currentRate = ((double)CurrentTotalBytes) / (1024 * seconds);
_currentStopwatch.Reset();
_currentStopwatch.Start();
CurrentTotalBytes = 0;
}
//---- Global rate
TotalBytes += length;
seconds = ((double)_globalStopwatch.ElapsedMilliseconds) / 1000;
_rate = ((double)TotalBytes) / (1024 * seconds);
}
catch (RUDPSocketException se)
{
OnTransportDisconnected_RUDP();
return;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
OnTransportDisconnected_RUDP();
return;
}
//---- Continue receive packets ... on the SAME socket, to insure
// we have completely read the socket buffer.
try
{
// if we have closed the socket between the 2 operations
if (!newRUDPSocket.Connected)
return;
// Restart receiving
newRUDPSocket.BeginReceive(new AsyncCallback(OnReceive_RUDP), Environment.TickCount);
}
catch (Exception e)
{
OnTransportDisconnected_RUDP();
return;
}
}
#endregion
#region OnReceive_TCP
internal void OnReceive_TCP(IAsyncResult result)
{
if (!newTCPSocket.Connected)
{
OnTransportDisconnected_TCP();
return;
}
//---- Process the received bytes
try
{
SocketError error = SocketError.Success;
int length = newTCPSocket.EndReceive(result);
//---- End of connection
if (length < 0)
{
// Connection closed by peer
OnTransportDisconnected_TCP();
return;
}
//---- Current rate
double seconds;
int now = Environment.TickCount;
CurrentTotalBytes += length;
if (_currentStopwatch.ElapsedMilliseconds > _currentRateInterval)
{
seconds = ((double)_currentStopwatch.ElapsedMilliseconds) / 1000;
_currentRate = ((double)CurrentTotalBytes) / (1024 * seconds);
_currentStopwatch.Reset();
_currentStopwatch.Start();
CurrentTotalBytes = 0;
}
//---- Global rate
TotalBytes += length;
seconds = ((double)_globalStopwatch.ElapsedMilliseconds) / 1000;
_rate = ((double)TotalBytes) / (1024 * seconds);
}
catch (SocketException se)
{
OnTransportDisconnected_TCP();
return;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
OnTransportDisconnected_TCP();
return;
}
//---- Continue receive packets ... on the SAME socket, to insure
// we have completely read the socket buffer.
try
{
// if we have closed the socket between the 2 operations
if (!newTCPSocket.Connected)
return;
// Restart receiving
newTCPSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive_TCP), Environment.TickCount);
}
catch (Exception e)
{
OnTransportDisconnected_TCP();
return;
}
}
#endregion
#region OnReceive_UDT
internal void OnReceive_UDT(IAsyncResult result)
{
if (!newUDTSocket.Connected)
{
OnTransportDisconnected_UDT();
return;
}
//---- Process the received bytes
try
{
SocketError error = SocketError.Success;
int length = newUDTSocket.EndReceive(result);
//---- End of connection
if (length < 0)
{
// Connection closed by peer
OnTransportDisconnected_UDT();
return;
}
//---- Current rate
double seconds;
int now = Environment.TickCount;
CurrentTotalBytes += length;
if (_currentStopwatch.ElapsedMilliseconds > _currentRateInterval)
{
seconds = ((double)_currentStopwatch.ElapsedMilliseconds) / 1000;
_currentRate = ((double)CurrentTotalBytes) / (1024 * seconds);
_currentStopwatch.Reset();
_currentStopwatch.Start();
CurrentTotalBytes = 0;
}
//---- Global rate
TotalBytes += length;
seconds = ((double)_globalStopwatch.ElapsedMilliseconds) / 1000;
_rate = ((double)TotalBytes) / (1024 * seconds);
}
catch (SocketException se)
{
OnTransportDisconnected_UDT();
return;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
OnTransportDisconnected_UDT();
return;
}
//---- Continue receive packets ... on the SAME socket, to insure
// we have completely read the socket buffer.
try
{
// if we have closed the socket between the 2 operations
if (!newUDTSocket.Connected)
return;
// Restart receiving
newUDTSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive_UDT), Environment.TickCount);
}
catch (Exception e)
{
OnTransportDisconnected_UDT();
return;
}
}
#endregion
#region OnTransportDisconnected_RUDP
private void OnTransportDisconnected_RUDP()
{
try
{
rudpSocket.Close();
}
catch { }
}
#endregion
#region OnTransportDisconnected_TCP
private void OnTransportDisconnected_TCP()
{
try
{
tcpSocket.Close();
}
catch { }
}
#endregion
#region OnTransportDisconnected_UDT
private void OnTransportDisconnected_UDT()
{
try
{
udtSocket.Close();
}
catch { }
}
#endregion
#region Closing
private void TCPServerForm_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
if (newTCPSocket != null)
newTCPSocket.Close();
if (newRUDPSocket != null)
newRUDPSocket.Close();
}
catch { }
try
{
thread.Abort();
}
catch { }
}
#endregion
#region trackBarZoom_Scroll
private void trackBarZoom_Scroll(object sender, EventArgs e)
{
if (trackBarZoom.Value < 1)
return;
performanceGraph.MaxPeekMagnitude = trackBarZoom.Value;
performanceGraph.UpdateGraph();
performanceGraph.MaxLabel = trackBarZoom.Value + "(Kb/s)";
labelZoom.Text = "Zoom : " + performanceGraph.MaxPeekMagnitude + " KB/s";
}
#endregion
}
}