Advertisement
coolman_bg84

Untitled

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