Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // State object for receiving data from remote device.
- public class StateObject : EventArgs
- {
- // Client socket.
- public Socket workSocket = null;
- // Size of receive buffer.
- public const int BufferSize = 512;
- // Receive buffer.
- public byte[] buffer = new byte[BufferSize];
- // Received data string.
- public StringBuilder sb = new StringBuilder();
- }
- public class SocketClass:ISocket
- {
- // ManualResetEvent instances signal completion.
- private ManualResetEvent connectDone =
- new ManualResetEvent(false);
- private ManualResetEvent sendDone =
- new ManualResetEvent(false);
- private ManualResetEvent receiveDone =
- new ManualResetEvent(false);
- public delegate void HandlerMessage(object ob, StateObject args);
- public event HandlerMessage ReciveMessage;
- private static Socket client;
- private string serverName;
- private int port;
- private string nickName;
- private string userName;
- private string botPrefixName;
- public SocketClass(IBotInfo info)
- {
- serverName = info.Servername;
- nickName = info.Nickname;
- userName = info.Username;
- port = info.Port;
- botPrefixName = info.BotPrefixName;
- }
- public SocketClass()
- {
- }
- public void StartClient()
- {
- // need for encoding win-1251!!!!
- Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
- try
- {
- // Connect to a remote device.
- IPHostEntry ipHostInfo = Dns.GetHostEntry(serverName);
- IPAddress ipAddress = ipHostInfo.AddressList[0];
- IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
- // Create a TCP/IP socket.
- client = new Socket(ipAddress.AddressFamily,
- SocketType.Stream, ProtocolType.Tcp);
- // Connect to the remote endpoint.
- client.BeginConnect(remoteEP,
- new AsyncCallback(ConnectCallback), client);
- connectDone.WaitOne();
- // Send test data to the remote device.
- Send(client, $"NICK {nickName}");
- Send(client, $"USER {userName}");
- sendDone.WaitOne();
- // Receive the response from the remote device.
- Receive(client);
- receiveDone.WaitOne();
- int q = 1;
- // System.IO.File.WriteAllText("WriteText.txt", response);
- // Release the socket.
- //client.Shutdown(SocketShutdown.Both);
- //client.Close();
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- }
- private void ConnectCallback(IAsyncResult ar)
- {
- try
- {
- // Retrieve the socket from the state object.
- Socket client = (Socket)ar.AsyncState;
- // Complete the connection.
- client.EndConnect(ar);
- Console.WriteLine("Socket connected to {0}",
- client.RemoteEndPoint.ToString());
- // Signal that the connection has been made.
- connectDone.Set();
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- }
- private void Receive(Socket client)
- {
- try
- {
- StateObject state = new StateObject();
- state.workSocket = client;
- // Begin receiving the data from the remote device.
- client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
- new AsyncCallback(ReceiveCallback), state);
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- }
- private void ReceiveCallback(IAsyncResult ar)
- {
- String content = String.Empty;
- // Retrieve the state object and the handler socket
- // from the asynchronous state object.
- StateObject state = (StateObject)ar.AsyncState;
- Socket handler = state.workSocket;
- // Read data from the client socket.
- int bytesRead = handler.EndReceive(ar);
- if (bytesRead > 0)
- {
- // convert received msg to win-1251 !!!!
- state.sb.Append(Encoding.GetEncoding("Windows-1251").GetString(
- state.buffer, 0, bytesRead));
- content = state.sb.ToString();
- // broadcast message if match exactly prefix and name of bot.
- //if (Regex.IsMatch(content, $@":({botPrefixName}) "))
- // OnReciveMessage(this, state);
- // broadcast message if match exactly the commands.
- if (MenuCommand.commands.Any(f => content.Contains(f)))
- {
- OnReciveMessage(this, state);
- }
- if (content.Contains("#dev"))
- {
- BotDBContext botDbContext = new BotDBContext();
- LogMessages logMessages = new LogMessages();
- logMessages.Channel = "#dev";
- logMessages.DateTime = DateTime.Now;
- logMessages.NickName = Regex.Match(content, @":(.+?)!").Groups[1].Value;
- logMessages.Message = Regex.Match(content, @".:(.+)\r\n").Groups[1].Value;
- botDbContext.Add(logMessages);
- botDbContext.SaveChanges();
- }
- if (content.Contains("PING"))
- {
- Send(handler, $"PONG ");
- sendDone.Set();
- }
- System.IO.File.WriteAllText(@"BotLog.txt", content);
- // Check for end-of-file tag. If it is not there, read
- // more data.
- if (content.IndexOf("\r\n", StringComparison.Ordinal) > -1)
- {
- Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
- state.sb.Clear();
- receiveDone.Set();
- }
- // Not all data received. Get more.
- handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
- new AsyncCallback(ReceiveCallback), state);
- }
- }
- public void Send(string msg)
- {
- Send(client, msg);
- }
- private void Send(Socket client, String data)
- {
- // convert encoding to Windows-1251 and at last line set \r\n
- byte[] byteData = Encoding.GetEncoding("Windows-1251").GetBytes(data + "\r\n");
- // Begin sending the data to the remote device.
- client.BeginSend(byteData, 0, byteData.Length, 0,
- new AsyncCallback(SendCallback), client);
- }
- private void SendCallback(IAsyncResult ar)
- {
- try
- {
- // Retrieve the socket from the state object.
- Socket client = (Socket)ar.AsyncState;
- // Complete sending the data to the remote device.
- int bytesSent = client.EndSend(ar);
- Console.WriteLine("Sent {0} bytes to server.", bytesSent);
- // Signal that all bytes have been sent.
- sendDone.Set();
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- }
- protected virtual void OnReciveMessage(object ob, StateObject args)
- {
- if (ReciveMessage != null)
- ReciveMessage?.Invoke(ob, args);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement