Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- protected void sendPORT(Socket socket)
- {
- // выбираем порт
- int iMin = 49152;
- int iMax = 65535;
- Random r = new Random();
- int port;
- do { port = iMin + r.Next(iMax - iMin); }
- while (checkPort(port));
- // делим на старший и младший байты
- int iPort1 = 0;
- int iPort2 = port;
- if (iPort2 > 255)
- {
- iPort1 = (int)(iPort2 / 256) * 256;
- iPort2 -= iPort1;
- }
- // локальный IP
- IPAddress localAddress = ((IPEndPoint)this.socket.LocalEndPoint).Address;
- // отправляем на сервер
- string command = string.Format("PORT {0},{1},{2}", localAddress.ToString().Replace('.', ','), iPort1, iPort2);
- Byte[] cmdBytes = enc.GetBytes(command.ToCharArray());
- socket.Send(cmdBytes, cmdBytes.Length, 0);
- createTCPListener(port);
- }
- private bool checkPort(int port)
- {
- // проверяем свободен ли порт
- // можно добавить еще условия
- throw new NotImplementedException();
- }
- private void createTCPListener(int port)
- {
- // здесь создаем и слушаем порт
- TcpListener server = new TcpListener(port);
- server.Start();
- Byte[] bytes = new Byte[256];
- String data = null;
- while (true)
- {
- TcpClient client = server.AcceptTcpClient();
- data = null;
- NetworkStream stream = client.GetStream();
- int i;
- while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
- {
- data = enc.GetString(bytes, 0, i);
- data = data.ToUpper();
- byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
- stream.Write(msg, 0, msg.Length);
- }
- // Shutdown and end connection
- client.Close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement