Advertisement
coolman_bg84

Untitled

Apr 7th, 2020
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.24 KB | None | 0 0
  1. // State object for receiving data from remote device.  
  2.     public class StateObject : EventArgs
  3.     {
  4.         // Client socket.  
  5.         public Socket workSocket = null;
  6.         // Size of receive buffer.  
  7.         public const int BufferSize = 512;
  8.         // Receive buffer.  
  9.         public byte[] buffer = new byte[BufferSize];
  10.         // Received data string.  
  11.         public StringBuilder sb = new StringBuilder();
  12.     }
  13.     public class SocketClass:ISocket
  14.     {
  15.         // ManualResetEvent instances signal completion.  
  16.         private ManualResetEvent connectDone =
  17.             new ManualResetEvent(false);
  18.         private ManualResetEvent sendDone =
  19.             new ManualResetEvent(false);
  20.         private ManualResetEvent receiveDone =
  21.             new ManualResetEvent(false);
  22.  
  23.         public delegate void HandlerMessage(object ob, StateObject args);
  24.         public event HandlerMessage ReciveMessage;
  25.  
  26.         private static Socket client;
  27.        
  28.         private string serverName;
  29.         private int port;
  30.         private string nickName;
  31.         private string userName;
  32.         private string botPrefixName;
  33.         public SocketClass(IBotInfo info)
  34.         {
  35.             serverName = info.Servername;
  36.             nickName = info.Nickname;
  37.             userName = info.Username;
  38.             port = info.Port;
  39.             botPrefixName = info.BotPrefixName;
  40.         }
  41.         public SocketClass()
  42.         {
  43.         }
  44.  
  45.         public void StartClient()
  46.         {
  47.             // need for encoding win-1251!!!!
  48.             Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  49.              
  50.             try
  51.             {
  52.                 // Connect to a remote device.
  53.                 IPHostEntry ipHostInfo = Dns.GetHostEntry(serverName);
  54.                 IPAddress ipAddress = ipHostInfo.AddressList[0];
  55.                 IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
  56.  
  57.                 // Create a TCP/IP socket.  
  58.                 client = new Socket(ipAddress.AddressFamily,
  59.                   SocketType.Stream, ProtocolType.Tcp);
  60.  
  61.                 // Connect to the remote endpoint.  
  62.                 client.BeginConnect(remoteEP,
  63.                     new AsyncCallback(ConnectCallback), client);
  64.                 connectDone.WaitOne();
  65.                
  66.                 // Send test data to the remote device.  
  67.                 Send(client, $"NICK {nickName}");
  68.  
  69.                 Send(client, $"USER {userName}");
  70.  
  71.                 sendDone.WaitOne();
  72.  
  73.                 // Receive the response from the remote device.  
  74.                 Receive(client);
  75.  
  76.                 receiveDone.WaitOne();
  77.  
  78.  
  79.                 int q = 1;
  80.                 // System.IO.File.WriteAllText("WriteText.txt", response);
  81.                 // Release the socket.  
  82.                 //client.Shutdown(SocketShutdown.Both);
  83.                 //client.Close();
  84.  
  85.             }
  86.             catch (Exception e)
  87.             {
  88.                 Console.WriteLine(e.ToString());
  89.             }
  90.         }
  91.         private void ConnectCallback(IAsyncResult ar)
  92.         {
  93.             try
  94.             {
  95.                 // Retrieve the socket from the state object.  
  96.                 Socket client = (Socket)ar.AsyncState;
  97.  
  98.                 // Complete the connection.  
  99.                 client.EndConnect(ar);
  100.  
  101.                 Console.WriteLine("Socket connected to {0}",
  102.                     client.RemoteEndPoint.ToString());
  103.  
  104.                 // Signal that the connection has been made.  
  105.                 connectDone.Set();
  106.             }
  107.             catch (Exception e)
  108.             {
  109.                 Console.WriteLine(e.ToString());
  110.             }
  111.         }
  112.         private void Receive(Socket client)
  113.         {
  114.             try
  115.             {
  116.                 StateObject state = new StateObject();
  117.                 state.workSocket = client;
  118.  
  119.                 // Begin receiving the data from the remote device.  
  120.                 client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  121.                     new AsyncCallback(ReceiveCallback), state);
  122.             }
  123.             catch (Exception e)
  124.             {
  125.                 Console.WriteLine(e.ToString());
  126.             }
  127.         }
  128.         private void ReceiveCallback(IAsyncResult ar)
  129.         {
  130.             String content = String.Empty;
  131.  
  132.             // Retrieve the state object and the handler socket  
  133.             // from the asynchronous state object.  
  134.             StateObject state = (StateObject)ar.AsyncState;
  135.             Socket handler = state.workSocket;
  136.  
  137.             // Read data from the client socket.
  138.             int bytesRead = handler.EndReceive(ar);
  139.  
  140.             if (bytesRead > 0)
  141.             {
  142.                 // convert received msg to win-1251 !!!!  
  143.                 state.sb.Append(Encoding.GetEncoding("Windows-1251").GetString(
  144.                     state.buffer, 0, bytesRead));
  145.  
  146.                 content = state.sb.ToString();
  147.  
  148.                 // broadcast message if match exactly prefix and name of bot.
  149.                 //if (Regex.IsMatch(content, $@":({botPrefixName}) "))
  150.                 //    OnReciveMessage(this, state);
  151.  
  152.                 // broadcast message if match exactly the commands.
  153.                 if (MenuCommand.commands.Any(f => content.Contains(f)))
  154.                 {
  155.                     OnReciveMessage(this, state);
  156.                    
  157.                 }
  158.  
  159.                 if (content.Contains("#dev"))
  160.                 {
  161.                     BotDBContext botDbContext = new BotDBContext();
  162.  
  163.                     LogMessages logMessages = new LogMessages();
  164.                      logMessages.Channel = "#dev";
  165.                      logMessages.DateTime = DateTime.Now;
  166.                      logMessages.NickName = Regex.Match(content, @":(.+?)!").Groups[1].Value;
  167.                     logMessages.Message = Regex.Match(content, @".:(.+)\r\n").Groups[1].Value;
  168.  
  169.  
  170.                     botDbContext.Add(logMessages);
  171.                     botDbContext.SaveChanges();
  172.                 }
  173.  
  174.                 if (content.Contains("PING"))
  175.                 {
  176.                     Send(handler, $"PONG ");
  177.                     sendDone.Set();
  178.                 }
  179.  
  180.                 System.IO.File.WriteAllText(@"BotLog.txt", content);
  181.                 // Check for end-of-file tag. If it is not there, read
  182.                 // more data.  
  183.                 if (content.IndexOf("\r\n", StringComparison.Ordinal) > -1)
  184.                 {
  185.                     Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
  186.                     state.sb.Clear();
  187.                     receiveDone.Set();
  188.                 }
  189.  
  190.                 // Not all data received. Get more.  
  191.                 handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  192.                     new AsyncCallback(ReceiveCallback), state);
  193.  
  194.             }
  195.         }
  196.  
  197.        
  198.         public void Send(string msg)
  199.         {
  200.             Send(client, msg);
  201.         }
  202.         private void Send(Socket client, String data)
  203.         {
  204.          
  205.             // convert encoding to Windows-1251 and at last line set \r\n
  206.             byte[] byteData = Encoding.GetEncoding("Windows-1251").GetBytes(data + "\r\n");
  207.  
  208.             // Begin sending the data to the remote device.  
  209.  
  210.             client.BeginSend(byteData, 0, byteData.Length, 0,
  211.                 new AsyncCallback(SendCallback), client);
  212.         }
  213.         private void SendCallback(IAsyncResult ar)
  214.         {
  215.             try
  216.             {
  217.                 // Retrieve the socket from the state object.  
  218.                 Socket client = (Socket)ar.AsyncState;
  219.  
  220.                 // Complete sending the data to the remote device.  
  221.                 int bytesSent = client.EndSend(ar);
  222.                 Console.WriteLine("Sent {0} bytes to server.", bytesSent);
  223.  
  224.                 // Signal that all bytes have been sent.  
  225.                 sendDone.Set();
  226.             }
  227.             catch (Exception e)
  228.             {
  229.                 Console.WriteLine(e.ToString());
  230.             }
  231.         }
  232.        
  233.         protected virtual void OnReciveMessage(object ob, StateObject args)
  234.         {
  235.             if (ReciveMessage != null)
  236.                 ReciveMessage?.Invoke(ob, args);
  237.         }
  238.        
  239.        
  240.      
  241.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement