Guest User

Untitled

a guest
Apr 20th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.IO;
  8. using System.Threading;
  9.  
  10. namespace SweatBand
  11. {
  12. class Server
  13. {
  14. private static TcpListener listener;
  15. private const int port = 1337;
  16.  
  17. public static void Start()
  18. {
  19. listener = new TcpListener(IPAddress.Any, port);
  20. listener.Start();
  21. Console.WriteLine("Server started on port " + port);
  22. ConnectionLoop();
  23. }
  24.  
  25. public static void ConnectionLoop()
  26. {
  27. while (true)
  28. {
  29. Socket client = listener.AcceptSocket();
  30. if (!client.Connected) return;
  31. ASCIIEncoding encoder = new ASCIIEncoding();
  32. byte[] message = new byte[4096];
  33. int bytesRead = 0;
  34.  
  35. int bytes = client.Receive(message, message.Length, SocketFlags.Peek);
  36. bytesRead = bytes;
  37.  
  38. //message has successfully been received
  39. string data = Encoding.ASCII.GetString(message, 0, bytesRead);
  40. Console.WriteLine(data);
  41.  
  42. SendToBrowser("hello", ref client);
  43.  
  44. client.Close();
  45. }
  46. }
  47.  
  48. public static void SendToBrowser(String sData, ref Socket mySocket)
  49. {
  50. SendToBrowser(Encoding.ASCII.GetBytes(sData), ref mySocket);
  51. }
  52.  
  53.  
  54. public static void SendToBrowser(Byte[] bSendData, ref Socket mySocket)
  55. {
  56. int numBytes = 0;
  57. try
  58. {
  59. if (mySocket.Connected)
  60. {
  61. if ((numBytes = mySocket.Send(bSendData,
  62. bSendData.Length, 0)) == -1)
  63. Console.WriteLine("Socket Error cannot Send Packet");
  64. else
  65. {
  66. Console.WriteLine("No. of bytes send {0}", numBytes);
  67. }
  68. }
  69. else
  70. Console.WriteLine("Connection Dropped....");
  71. }
  72. catch (Exception e)
  73. {
  74. Console.WriteLine("Error Occurred : {0} ", e);
  75. }
  76. }
  77. }
  78. }
Add Comment
Please, Sign In to add comment