Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.38 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. using System.Net.Sockets;
  7. using System.Net;
  8. using System.Threading;
  9.  
  10.  
  11.  
  12. namespace SocketLibrary.WP
  13. {
  14.     public class SocketClient
  15.     {
  16.         private Socket _socket = null;
  17.         static ManualResetEvent clientDone = new ManualResetEvent(false);
  18.  
  19.         public Socket GetSocket
  20.         {
  21.             get { return _socket; }
  22.         }
  23.  
  24.         const int TIMEOUT_MILLISECONDS = 5000;
  25.  
  26.         public string Connect(string serverName, int port, bool useTcp)
  27.         {
  28.             string result= string.Empty;
  29.             //DnsEndPoint hostEntry = new DnsEndPoint(serverName, port);
  30.             IPEndPoint hostEntry = new IPEndPoint(IPAddress.Parse(serverName), port);
  31.  
  32.             ProtocolType protocol = useTcp ? ProtocolType.Tcp : ProtocolType.Udp;
  33.             Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, protocol);
  34.  
  35.             SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs();
  36.             socketEventArgs.RemoteEndPoint = hostEntry;
  37.             socketEventArgs.UserToken = sock;
  38.             socketEventArgs.Completed +=new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs sae)
  39.                 {
  40.                     _socket = sae.UserToken as Socket;
  41.                     result = sae.SocketError.ToString();
  42.                     clientDone.Set();
  43.                 });
  44.  
  45.             clientDone.Reset();
  46.             sock.ConnectAsync(socketEventArgs);
  47.             clientDone.WaitOne(TIMEOUT_MILLISECONDS);
  48.  
  49.             return result;
  50.         }
  51.  
  52.         public void Disconnect()
  53.         {
  54.             _socket.Close(TIMEOUT_MILLISECONDS);
  55.         }
  56.  
  57.         public string Send(string message)
  58.         {
  59.             string result = "Socket is not initialized";
  60.             if (_socket != null)
  61.             {
  62.                 SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
  63.                 socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
  64.                 socketEventArg.UserToken = null;
  65.                 socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs sae)
  66.                 {
  67.                     result = sae.SocketError.ToString();
  68.                     clientDone.Set();
  69.                 });
  70.  
  71.                 byte[] payload = Encoding.UTF8.GetBytes(message + "<EOF>");
  72.                 socketEventArg.SetBuffer(payload, 0, payload.Length);
  73.  
  74.                 clientDone.Reset();
  75.                 _socket.SendAsync(socketEventArg);
  76.                 clientDone.WaitOne(TIMEOUT_MILLISECONDS);
  77.             }
  78.  
  79.             return result;
  80.         }
  81.  
  82.         public string Receive()
  83.         {
  84.             string response = "Nothing ";
  85.             if (_socket != null)
  86.             {
  87.                 SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
  88.                 socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
  89.                 socketEventArg.UserToken = null;
  90.                 socketEventArg.SetBuffer(new Byte[64], 0, 64);
  91.                 socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs sae)
  92.                 {
  93.                     response = Encoding.UTF8.GetString(sae.Buffer, 0, sae.BytesTransferred);
  94.                     response = response.Replace("<EOF>", "");
  95.                     clientDone.Set();
  96.                 });
  97.  
  98.                 clientDone.Reset();
  99.                 _socket.ReceiveAsync(socketEventArg);
  100.                 clientDone.WaitOne(TIMEOUT_MILLISECONDS);
  101.             }
  102.  
  103.             return response;
  104.         }
  105.  
  106.     }
  107. }
  108.  
  109.  
  110.  
  111. using System;
  112. using System.Collections.Generic;
  113. using System.Linq;
  114. using System.Text;
  115.  
  116. using System.Net.Sockets;
  117. using System.Net;
  118. using System.Threading;
  119.  
  120. namespace SocketLibrary.WP
  121. {
  122.     // State object for reading client data asynchronously
  123.     public class StateObject
  124.     {
  125.         // Client  socket.
  126.         public Socket workSocket = null;
  127.         // Size of receive buffer.
  128.         public const int BufferSize = 1024;
  129.         // Receive buffer.
  130.         public byte[] buffer = new byte[BufferSize];
  131.         // Received data string.
  132.         public StringBuilder sb = new StringBuilder();
  133.     }
  134.  
  135.     public class SocketServer
  136.     {
  137.         const int TIMEOUT_MILLISECONDS = 5000;
  138.  
  139.         // Thread signal.
  140.         public static ManualResetEvent allDone = new ManualResetEvent(false);
  141.  
  142.         public SocketServer()
  143.         {
  144.         }
  145.  
  146.         public void StartListening()
  147.         {
  148.             // Data buffer for incoming data.
  149.             byte[] bytes = new Byte[1024];
  150.  
  151.             // Establish the local endpoint for the socket.
  152.             // The DNS name of the computer
  153.             // running the listener is "host.contoso.com".
  154.  
  155.             IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 222);
  156.  
  157.             // Create a TCP/IP socket.
  158.             Socket listener = new Socket(AddressFamily.InterNetwork,
  159.                 SocketType.Stream, ProtocolType.Tcp);
  160.  
  161.             // Bind the socket to the local endpoint and listen for incoming connections.
  162.             try
  163.             {
  164.                 listener.Bind(localEndPoint);
  165.                 listener.Listen(10);
  166.  
  167.                 while (true)
  168.                 {
  169.                     // Set the event to nonsignaled state.
  170.                     allDone.Reset();
  171.  
  172.                     // Start an asynchronous socket to listen for connections.
  173.                     Console.WriteLine("Waiting for a connection...");
  174.                     listener.BeginAccept(
  175.                         new AsyncCallback(AcceptCallback),
  176.                         listener);
  177.  
  178.                     // Wait until a connection is made before continuing.
  179.                     allDone.WaitOne();
  180.                 }
  181.  
  182.             }
  183.             catch (Exception e)
  184.             {
  185.                 Console.WriteLine(e.ToString());
  186.             }
  187.  
  188.             Console.WriteLine("\nPress ENTER to continue...");
  189.             Console.Read();
  190.  
  191.         }
  192.  
  193.         public void AcceptCallback(IAsyncResult ar)
  194.         {
  195.             // Signal the main thread to continue.
  196.             allDone.Set();
  197.  
  198.             // Get the socket that handles the client request.
  199.             Socket listener = (Socket)ar.AsyncState;
  200.             Socket handler = listener.EndAccept(ar);
  201.  
  202.             // Create the state object.
  203.             StateObject state = new StateObject();
  204.             state.workSocket = handler;
  205.             handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  206.                 new AsyncCallback(ReadCallback), state);
  207.         }
  208.  
  209.         public void ReadCallback(IAsyncResult ar)
  210.         {
  211.             String content = String.Empty;
  212.  
  213.             // Retrieve the state object and the handler socket
  214.             // from the asynchronous state object.
  215.             StateObject state = (StateObject)ar.AsyncState;
  216.             Socket handler = state.workSocket;
  217.  
  218.             // Read data from the client socket.
  219.             int bytesRead = handler.EndReceive(ar);
  220.  
  221.             if (bytesRead > 0)
  222.             {
  223.                 // There  might be more data, so store the data received so far.
  224.                 state.sb.Append(Encoding.UTF8.GetString(
  225.                     state.buffer, 0, bytesRead));
  226.  
  227.                 // Check for end-of-file tag. If it is not there, read
  228.                 // more data.
  229.                 content = state.sb.ToString();
  230.                 if (content.IndexOf("<EOF>") > -1)
  231.                 {
  232.                     // All the data has been read from the
  233.                     // client. Display it on the console.
  234.                     Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
  235.                         content.Length, content);
  236.                     // Echo the data back to the client.
  237.                     Send(handler, content);
  238.                 }
  239.                 else
  240.                 {
  241.                     // Not all data received. Get more.
  242.                     handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  243.                     new AsyncCallback(ReadCallback), state);
  244.                 }
  245.             }
  246.         }
  247.  
  248.         private void Send(Socket handler, String data)
  249.         {
  250.             data = String.Format("You Sent: '{0}'", data);
  251.             //data = data.Replace("<EOF>", "");
  252.             // data = GameLogic.Play(data);
  253.             // Convert the string data to byte data using ASCII encoding.
  254.             byte[] byteData = Encoding.UTF8.GetBytes(data);
  255.  
  256.             // Begin sending the data to the remote device.
  257.             handler.BeginSend(byteData, 0, byteData.Length, 0,
  258.                 new AsyncCallback(SendCallback), handler);
  259.         }
  260.        
  261.         private void SendCallback(IAsyncResult ar)
  262.         {
  263.             try
  264.             {
  265.                 // Retrieve the socket from the state object.
  266.                 Socket handler = (Socket)ar.AsyncState;
  267.  
  268.                 // Complete sending the data to the remote device.
  269.                 int bytesSent = handler.EndSend(ar);
  270.                 Console.WriteLine("Sent {0} bytes to client.", bytesSent);
  271.  
  272.                 handler.Shutdown(SocketShutdown.Both);
  273.                 handler.Close();
  274.  
  275.             }
  276.             catch (Exception e)
  277.             {
  278.                 Console.WriteLine(e.ToString());
  279.             }
  280.         }
  281.  
  282.     }
  283. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement