[C#] Socket Server Class
I wrote this up real quick because I lacked I a socket class at the time.
Overall, I think it's decent. Please post area's where I can improve and your suggestions.
It automatically expands the array of connections for unlimited connections. I chose arrays because I was also trying to make this cross-platform because of Mono and I'm not sure if Mono has all of the Collections elements.
Updated: 3/29/2013
Overall, I think it's decent. Please post area's where I can improve and your suggestions.
It automatically expands the array of connections for unlimited connections. I chose arrays because I was also trying to make this cross-platform because of Mono and I'm not sure if Mono has all of the Collections elements.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Sockets
{
#region Client Interface
class SocketClient
{
#region Declarings
Socket client_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public SocketOptions socket_options = null;
public delegate void NewPacketHandler(string received_remote_ip, string received_local_ip, string packet_data);
public event NewPacketHandler new_packet;
#endregion
public Boolean Connect(string ip_address, int port)
{
try
{
client_socket.Connect(new IPEndPoint(IPAddress.Parse(ip_address), port));
return client_socket.Connected;
}
catch
{
return client_socket.Connected;
}
}
public void Disconnect()
{
client_socket.Disconnect(true);
}
public void Send(string data, int offset, int size, int timeout)
{
int startTickCount = Environment.TickCount;
int sent = 0;
do
{
if (Environment.TickCount > startTickCount + timeout)
throw new Exception("Failed to send packet - time out");
try
{
sent += client_socket.Send(Encoding.UTF8.GetBytes(data + socket_options.Terminator), offset + sent, size - sent, SocketFlags.None);
}
catch (Exception ex)
{
Console.WriteLine("ERROR: " + ex.Message);
}
} while (sent < size);
}
public void Send(string packet_data)
{
Send(packet_data, 0, packet_data.Length, 10000);
}
public void Get()
{
try
{
byte[] Buffer = new byte[client_socket.SendBufferSize];
int bytes_read = client_socket.Receive(Buffer);
byte[] bytesFormatted = new byte[bytes_read];
for (int i = 0; i < bytes_read; i++)
bytesFormatted[i] = Buffer[i];
string received_data = Encoding.UTF8.GetString(bytesFormatted);
if (received_data[received_data.Length - 1] == socket_options.Terminator)
{
string[] received_data_split = received_data.Split(socket_options.Terminator);
foreach (string string_data in received_data_split)
{
OnPacketRecieved(IPAddress.Parse(((IPEndPoint)client_socket.RemoteEndPoint).Address.ToString()), IPAddress.Parse(((IPEndPoint)client_socket.LocalEndPoint).Address.ToString()), string_data);
}
}
else
{
OnPacketRecieved(IPAddress.Parse(((IPEndPoint)client_socket.RemoteEndPoint).Address.ToString()), IPAddress.Parse(((IPEndPoint)client_socket.LocalEndPoint).Address.ToString()), received_data);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void OnPacketRecieved(IPAddress received_ip_address, IPAddress received_local_ip, string received_data)
{
if (received_data != null & new_packet != null)
new_packet(received_ip_address.ToString(), received_local_ip.ToString(), received_data);
}
}
#endregion
#region Socket Interface
class SocketInterface
{
#region Declarings
Socket main_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket[] accept_socket = new Socket[100];
Thread thread_listen = null;
public SocketOptions socket_options = null;
public delegate void NewConnectionHandler(object sender, string remote_ip, string local_ip);
public event NewConnectionHandler new_connection;
public delegate void NewPacketHandler(int index, string received_remote_ip, string received_local_ip, string packet_data);
public event NewPacketHandler new_packet;
public string[,] connections = new string[1, 3];
private int capacity = 100;
#endregion
public SocketInterface()
{
}
public void Start()
{
thread_listen = new Thread(listen_handler);
thread_listen.Start();
}
public void Stop()
{
if (thread_listen.IsAlive)
thread_listen.Abort();
}
public void Disconnect(int index)
{
if (accept_socket[index].Connected)
accept_socket[index].Disconnect(true);
}
public void Disconnect(string ip_address)
{
int index = Connection_Index(ip_address);
if (accept_socket[index].Connected)
accept_socket[index].Disconnect(true);
}
public void Disconnect()
{
if (main_socket.Connected == true)
main_socket.Disconnect(true);
for (int i = 0; i < capacity; i++)
{
try
{
if (connections[i, 2] != null)
{
accept_socket[i].Disconnect(true);
connections[i, 2] = null;
}
}
catch { }
}
}
private void listen_handler()
{
try
{
main_socket.Bind(new IPEndPoint(IPAddress.Parse(socket_options.IPAddress), socket_options.Port));
main_socket.Listen(socket_options.Backlog);
while (true)
{
Thread.Sleep(500);
main_socket.BeginAccept(
new AsyncCallback(Accept),
main_socket);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public int Find_Open()
{
for (int i = 0; i < capacity; i++)
{
if (connections[i, 2] == null)
return i;
}
return -1;
}
private void Resize()
{
string[,] temp_array = new string[capacity + 2, 3];
capacity = capacity + 2;
Array.Copy(connections, temp_array, connections.Length);
connections = temp_array;
}
private void Accept(IAsyncResult ar)
{
int open_index = Find_Open();
Resize();
main_socket.BeginAccept(
new AsyncCallback(Accept),
main_socket);
accept_socket[open_index] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
main_socket = (Socket)ar.AsyncState;
accept_socket[open_index] = main_socket.EndAccept(ar);
IPAddress remote_ip = IPAddress.Parse(((IPEndPoint)accept_socket[open_index].RemoteEndPoint).Address.ToString());
IPAddress local_ip = IPAddress.Parse(((IPEndPoint)accept_socket[open_index].LocalEndPoint).Address.ToString());
connections[open_index, 0] = remote_ip.ToString();
connections[open_index, 1] = local_ip.ToString();
connections[open_index, 2] = "connected";
OnConnectSuccess(remote_ip.ToString(), local_ip.ToString());
}
public bool Connected(int Index)
{
return accept_socket[index].Connected;
}
public bool Connected(string remote_ip)
{
return accept_socket[Connection_Index(remote_ip)].Connected;
}
public bool Connected(string remote_ip, string local_ip)
{
return accept_socket[Connection_Index(remote_ip, local_ip)].Connected;
}
public int Connection_Index(string remote_ip, string local_ip)
{
for (int i = 0; i < capacity; i++)
{
if ((remote_ip == connections[i, 0]) && (local_ip == connections[i, 1]))
return i;
}
return -1;
}
public int Connection_Index(string ip_address)
{
for (int i = 0; i < capacity; i++)
{
if ((ip_address == connections[i, 0]) || (ip_address == connections[i, 1]))
return i;
}
return -1;
}
public void Send(int index, string data, int offset, int size, int timeout)
{
int startTickCount = Environment.TickCount;
int sent = 0;
while (sent < size)
{
if (Environment.TickCount > startTickCount + timeout)
throw new Exception("Timed out: " + index);
try
{
sent += accept_socket[index].Send(Encoding.UTF8.GetBytes(data + socket_options.Terminator), offset + sent, size - sent, SocketFlags.None);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
public void Send(int index, string data)
{
Send(index, data, 0, data.Length, 10000);
}
public void Get(int index)
{
try
{
byte[] Buffer = new byte[accept_socket[index].SendBufferSize];
int bytes_read = accept_socket[index].Receive(Buffer);
byte[] bytesFormatted = new byte[bytes_read];
for (int i = 0; i < bytes_read; i++)
bytesFormatted[i] = Buffer[i];
string received_data = Encoding.UTF8.GetString(bytesFormatted);
if (received_data[received_data.Length - 1] == socket_options.Terminator)
{
string[] received_data_split = received_data.Split(socket_options.Terminator);
foreach (string string_data in received_data_split)
{
OnPacketRecieved(index, IPAddress.Parse(((IPEndPoint)accept_socket[index].RemoteEndPoint).Address.ToString()), IPAddress.Parse(((IPEndPoint)accept_socket[index].LocalEndPoint).Address.ToString()), string_data);
}
}
else
{
OnPacketRecieved(index, IPAddress.Parse(((IPEndPoint)accept_socket[index].RemoteEndPoint).Address.ToString()), IPAddress.Parse(((IPEndPoint)accept_socket[index].LocalEndPoint).Address.ToString()), received_data);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void OnPacketRecieved(int index, IPAddress received_ip_address, IPAddress received_local_ip, string received_data)
{
if (received_data != null & new_packet != null)
new_packet(index, received_ip_address.ToString(), received_local_ip.ToString(), received_data);
}
private void OnConnectSuccess(string received_remote_ip, string received_local_ip)
{
if (new_connection != null)
new_connection(this, received_remote_ip, received_local_ip);
}
}
#endregion
#region Socket Options
class SocketOptions
{
#region Declarings
private string listen_ip = "127.0.0.1";
private char packet_terminator = (char)'\0';
private int listen_port = 2262;
private int listen_amount = 5;
#endregion
#region Functions
public string IPAddress
{
get { return listen_ip; }
set { listen_ip = value; }
}
public char Terminator
{
get { return packet_terminator; }
set { packet_terminator = value; }
}
public int Port
{
get { return listen_port; }
set { listen_port = value; }
}
public int Backlog
{
get { return listen_amount; }
set { listen_amount = value; }
}
#endregion
}
#endregion
}
[/index][/index][/index][/index][/i][/i][/index][/index][/index][/index][/i][/index][/index][/index][/index][/100][/i][/i]Updated: 3/29/2013