Advertisement
Guest User

Untitled

a guest
Jul 29th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. protected void sendPORT(Socket socket)
  2. {
  3. // выбираем порт
  4. int iMin = 49152;
  5. int iMax = 65535;
  6. Random r = new Random();
  7. int port;
  8. do { port = iMin + r.Next(iMax - iMin); }
  9. while (checkPort(port));
  10.  
  11. // делим на старший и младший байты
  12. int iPort1 = 0;
  13. int iPort2 = port;
  14. if (iPort2 > 255)
  15. {
  16. iPort1 = (int)(iPort2 / 256) * 256;
  17. iPort2 -= iPort1;
  18. }
  19. // локальный IP
  20. IPAddress localAddress = ((IPEndPoint)this.socket.LocalEndPoint).Address;
  21. // отправляем на сервер
  22. string command = string.Format("PORT {0},{1},{2}", localAddress.ToString().Replace('.', ','), iPort1, iPort2);
  23. Byte[] cmdBytes = enc.GetBytes(command.ToCharArray());
  24. socket.Send(cmdBytes, cmdBytes.Length, 0);
  25.  
  26. createTCPListener(port);
  27. }
  28.  
  29. private bool checkPort(int port)
  30. {
  31. // проверяем свободен ли порт
  32. // можно добавить еще условия
  33. throw new NotImplementedException();
  34. }
  35.  
  36. private void createTCPListener(int port)
  37. {
  38. // здесь создаем и слушаем порт
  39.  
  40. TcpListener server = new TcpListener(port);
  41. server.Start();
  42.  
  43. Byte[] bytes = new Byte[256];
  44. String data = null;
  45.  
  46. while (true)
  47. {
  48. TcpClient client = server.AcceptTcpClient();
  49. data = null;
  50. NetworkStream stream = client.GetStream();
  51. int i;
  52. while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
  53. {
  54. data = enc.GetString(bytes, 0, i);
  55. data = data.ToUpper();
  56. byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
  57. stream.Write(msg, 0, msg.Length);
  58. }
  59.  
  60. // Shutdown and end connection
  61. client.Close();
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement