Advertisement
lukicdarkoo

LDSocket (Socket client and server)

Mar 4th, 2013
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.34 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5.  
  6. namespace LDSocket
  7. {
  8.     class SocketClient
  9.     {
  10.         /*
  11.          * Coded by Darko Lukic
  12.          * 17:36 24. 2. 2013.
  13.          *
  14.          * Reference: http://www.codeguru.com/csharp/csharp/cs_misc/sampleprograms/article.php/c7695/Asynchronous-Socket-Programming-in-C-Part-I.htm
  15.          */
  16.  
  17.  
  18.  
  19.         /*
  20.            Invoke(new MethodInvoker(
  21.                 delegate
  22.                 {
  23.                 }
  24.             ));
  25.          */
  26.  
  27.  
  28.         public string ip;
  29.         private int port;
  30.         public string breakChar;
  31.         public bool connected = false;
  32.  
  33.         private Socket socket;
  34.         private AsyncCallback callBack;
  35.         private IAsyncResult result;
  36.         private string receivedData = "";
  37.  
  38.         public delegate void DataReceivedHandler(string data);
  39.         public event DataReceivedHandler DataReceived;
  40.  
  41.         public class SocketPacket
  42.         {
  43.             public Socket socket;
  44.             public byte[] dataBuffer = new byte[1];
  45.         }
  46.  
  47.         public SocketClient(string _ip, int _port = 8000, string _breakChar = "$")
  48.         {
  49.             ip = _ip;
  50.             port = _port;
  51.             breakChar = _breakChar;
  52.         }
  53.  
  54.         public bool connect()
  55.         {
  56.             if (connected)
  57.                 disconnect();
  58.  
  59.             try
  60.             {
  61.                 socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  62.                 socket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
  63.  
  64.                 callBack = new AsyncCallback(OnByteReceived);
  65.  
  66.                 if (socket.Connected)
  67.                     WaitForData();
  68.  
  69.                 return true;
  70.                 connected = true;
  71.             }
  72.             catch { return false; connected = false; }
  73.         }
  74.  
  75.         public void disconnect()
  76.         {
  77.             socket.Dispose();
  78.             receivedData = "";
  79.             connected = false;
  80.         }
  81.  
  82.         private void WaitForData()
  83.         {
  84.             try
  85.             {
  86.                 SocketPacket socketPacket = new SocketPacket();
  87.                 socketPacket.socket = socket;
  88.  
  89.                 result = socket.BeginReceive(socketPacket.dataBuffer, 0, socketPacket.dataBuffer.Length, SocketFlags.None, callBack, socketPacket);
  90.             }
  91.             catch { }
  92.         }
  93.  
  94.  
  95.         private void OnByteReceived(IAsyncResult asyn)
  96.         {
  97.             try
  98.             {
  99.                 SocketPacket socketPacket = (SocketPacket)asyn.AsyncState;
  100.                 string receivedChar = Convert.ToChar(socketPacket.dataBuffer[0]).ToString();
  101.  
  102.                 if (receivedChar == breakChar)
  103.                 {
  104.                     DataReceived(receivedData);
  105.                     receivedData = "";
  106.                 }
  107.                 else receivedData += receivedChar;
  108.  
  109.  
  110.                 WaitForData();
  111.             }
  112.             catch (ObjectDisposedException)
  113.             {
  114.                 //connection lost
  115.             }
  116.         }
  117.  
  118.         public void sendMessage(string data)
  119.         {
  120.             try
  121.             {
  122.                 socket.Send(System.Text.Encoding.ASCII.GetBytes(data + breakChar));
  123.             }
  124.             catch { }
  125.         }
  126.     }
  127.  
  128.  
  129.  
  130.  
  131.  
  132.     /*
  133.      * Coded by Darko Lukic
  134.      * 17:01 24. 2. 2013.
  135.      *
  136.      * Reference: http://www.codeguru.com/csharp/csharp/cs_misc/sampleprograms/article.php/c7695/Asynchronous-Socket-Programming-in-C-Part-I.htm
  137.      */
  138.  
  139.     class SocketServer
  140.     {
  141.         public int port;
  142.         public bool active = false;
  143.         public string breakChar;
  144.  
  145.         public int count { get { return sockets.Count; } }
  146.  
  147.         private AsyncCallback clientCallBack;
  148.         private Socket mainSocket;
  149.         private List<Socket> sockets = new List<Socket>();
  150.         private List<string> socketsData = new List<string>();
  151.  
  152.  
  153.         public delegate void DataReceivedHandler(string data, int index);
  154.         public event DataReceivedHandler DataReceived;
  155.  
  156.         public delegate void ClientConnectinChangedHandler(bool state, int index);
  157.         public event ClientConnectinChangedHandler ClientConnectionChanged;
  158.  
  159.  
  160.         public SocketServer(int _port = 8000, string _breakChar = "$")
  161.         {
  162.             port = _port;
  163.             breakChar = _breakChar;
  164.  
  165.             start();
  166.         }
  167.  
  168.         public void start()
  169.         {
  170.             if (active)
  171.                 stop();
  172.  
  173.             try
  174.             {
  175.                 mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  176.                 mainSocket.Bind(new IPEndPoint(IPAddress.Any, port));
  177.                 mainSocket.Listen(4);
  178.                 mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  179.  
  180.                 clientCallBack = new AsyncCallback(OnByteReceived);
  181.  
  182.                 active = true;
  183.             }
  184.             catch { active = false; }
  185.         }
  186.  
  187.         public void stop()
  188.         {
  189.             mainSocket.Dispose();
  190.             sockets.Clear();
  191.             socketsData.Clear();
  192.  
  193.             active = false;
  194.         }
  195.  
  196.         private void OnClientConnect(IAsyncResult asyn)
  197.         {
  198.             try
  199.             {
  200.                 sockets.Add(mainSocket.EndAccept(asyn));
  201.                 socketsData.Add("");
  202.  
  203.                 try { ClientConnectionChanged(true, sockets.Count - 1); }
  204.                 catch { }
  205.  
  206.                 WaitForData(sockets[sockets.Count - 1], sockets.Count - 1);
  207.  
  208.                 mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  209.             }
  210.             catch (ObjectDisposedException)
  211.             {
  212.                 try
  213.                 {
  214.                     ClientConnectionChanged(false, sockets.Count - 1);
  215.                 }
  216.                 catch { }
  217.             }
  218.         }
  219.  
  220.         private void WaitForData(Socket socket, int index)
  221.         {
  222.             try
  223.             {
  224.                 SocketPacket socketPacket = new SocketPacket();
  225.                 socketPacket.socket = socket;
  226.                 socketPacket.index = index;
  227.  
  228.                 socket.BeginReceive(socketPacket.dataBuffer, 0, socketPacket.dataBuffer.Length, SocketFlags.None, clientCallBack, socketPacket);
  229.             }
  230.             catch
  231.             {
  232.                 try
  233.                 {
  234.                     ClientConnectionChanged(false, index);
  235.                 }
  236.                 catch { }
  237.             }
  238.         }
  239.  
  240.         private class SocketPacket
  241.         {
  242.             public int index;
  243.             public Socket socket;
  244.             public byte[] dataBuffer = new byte[1];
  245.         }
  246.  
  247.  
  248.         private void OnByteReceived(IAsyncResult asyn)
  249.         {
  250.             SocketPacket socketPacket = (SocketPacket)asyn.AsyncState;
  251.  
  252.             try
  253.             {
  254.                 string receivedChar = Convert.ToChar(socketPacket.dataBuffer[0]).ToString();
  255.  
  256.                 if (receivedChar == breakChar)
  257.                 {
  258.                     DataReceived(socketsData[socketPacket.index], socketPacket.index);
  259.  
  260.                     socketsData[socketPacket.index] = "";
  261.                 }
  262.                 else socketsData[socketPacket.index] += receivedChar;
  263.  
  264.  
  265.                 WaitForData(socketPacket.socket, socketPacket.index);
  266.             }
  267.             catch (ObjectDisposedException)
  268.             {
  269.                 try
  270.                 {
  271.                     ClientConnectionChanged(false, socketPacket.index);
  272.                 }
  273.                 catch { }
  274.             }
  275.         }
  276.  
  277.  
  278.         public void sendMessage(string data, int index = -1)
  279.         {
  280.             try
  281.             {
  282.                 if (index == -1)
  283.                 {
  284.                     foreach (Socket socket in sockets)
  285.                     {
  286.                         try
  287.                         {
  288.                             socket.Send(System.Text.Encoding.ASCII.GetBytes(data + breakChar));
  289.                         }
  290.                         catch { }
  291.                     }
  292.                 }
  293.  
  294.                 else
  295.                 {
  296.                     try
  297.                     {
  298.                         sockets[index].Send(System.Text.Encoding.ASCII.GetBytes(data + breakChar));
  299.                     }
  300.                     catch { }
  301.                 }
  302.             }
  303.  
  304.             catch { }
  305.         }
  306.     }
  307. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement