Skip to content

Instantly share code, notes, and snippets.

@louis-e
Forked from darkguy2008/UDPSocket.cs
Last active April 14, 2024 02:43
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save louis-e/888d5031190408775ad130dde353e0fd to your computer and use it in GitHub Desktop.
Save louis-e/888d5031190408775ad130dde353e0fd to your computer and use it in GitHub Desktop.
Simple C# UDP server/client in 62 lines
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace UDP
{
public class UDPSocket
{
public Socket _socket;
private const int bufSize = 8 * 1024;
private State state = new State();
private EndPoint epFrom = new IPEndPoint(IPAddress.Any, 0);
private AsyncCallback recv = null;
public class State
{
public byte[] buffer = new byte[bufSize];
}
public void Server(string address, int port)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
_socket.Bind(new IPEndPoint(IPAddress.Parse(address), port));
Receive();
}
public void Client(string address, int port)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_socket.Connect(IPAddress.Parse(address), port);
Receive();
}
public void Send(string text)
{
byte[] data = Encoding.ASCII.GetBytes(text);
_socket.BeginSend(data, 0, data.Length, SocketFlags.None, (ar) =>
{
State so = (State)ar.AsyncState;
int bytes = _socket.EndSend(ar);
Console.WriteLine("SEND: {0}, {1}", bytes, text);
}, state);
}
private void Receive()
{
_socket.BeginReceiveFrom(state.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv = (ar) =>
{
try
{
State so = (State)ar.AsyncState;
int bytes = _socket.EndReceiveFrom(ar, ref epFrom);
_socket.BeginReceiveFrom(so.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv, so);
Console.WriteLine("RECV: {0}: {1}, {2}", epFrom.ToString(), bytes, Encoding.ASCII.GetString(so.buffer, 0, bytes));
} catch { }
}, state);
}
}
}
using System;
namespace UDP
{
class Program
{
static void Main(string[] args)
{
UDPSocket s = new UDPSocket();
s.Server("127.0.0.1", 27000);
UDPSocket c = new UDPSocket();
c.Client("127.0.0.1", 27000);
c.Send("TEST!");
Console.ReadKey();
s._socket.Close(); //Fixed closing bug (System.ObjectDisposedException)
//Bugfix allows to relaunch server
Console.WriteLine("Closed Server \n Press any key to exit");
Console.ReadKey();
}
}
}
Copy link

ghost commented Apr 22, 2020

_socket must be a public value, otherwise usage can't read it

@louis-e
Copy link
Author

louis-e commented Apr 22, 2020

_socket must be a public value, otherwise usage can't read it

You're right, thank you. I don't know why I didn't discovered it earlier. I made a revision :)

@DimitarBogdanov
Copy link

Perfect. Thank you so much!

@wolfi-by
Copy link

I think it would be better to implement IDispsable. Thus _socket can stay private

@louis-e
Copy link
Author

louis-e commented Aug 31, 2021

I think it would be better to implement IDispsable. Thus _socket can stay private

Good idea, thanks! I might be able to implement it in the next few weeks.

@eastudio-1990
Copy link

nice Code - thanks ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment