5

我正在使用一个通过 TCP 协议接收文件的应用程序,应用程序处理文件然后通过相同的协议发送它,我正在接收文件没有问题,我的问题是当我尝试发送文件时,因为我需要将文件发送到另一个正在侦听动态端口的应用程序,我用来发送这些文件的代码是:

internal void Send(byte[] buffer)
    {
        TcpClient _client = null;
        try
        {
            _client = new TcpClient(RemoteIPaddress, Dynamic_port);

            if (_client != null)
            {
                NetworkStream _clienttStream = _client.GetStream();
                _clienttStream.Write(buffer, 0, buffer.Length);
                _clienttStream.Flush();
                _clienttStream.Close();
                _clienttStream = null;
            }
        }
        catch 
        {
            if (_client != null)
            {
                _client.Close();
                _client = null;
            }
        }
    }

问题是,如何通过 TCP 协议将文件发送到使用动态端口的远程机器

4

2 回答 2

2

Typically, the server should listen on a well known port for a connection request. The response should include the port number that the server will communicate further on. Then your app connects to that port for transferring the data.

The communication should do the following:

  1. Client connects to server on well known port.
  2. Server responds with the dynamic port number to use for further communication.
  3. Client connects to server on the received port number.
  4. Server responds stating connection established.
  5. Client transmits data and disconnects.

This is a simplified version of how passive FTP works.

Point is, there are only two ways to connect to a server on a dynamic port. The first way is outlined above. If you can't do it that way then your client app will have to do a port scan, sending a connection attempt to every port within a range, and see which one the server responds on. However, firewalls are generally programmed to notice this type of thing and shut you down (it's hacker behavior).

于 2012-04-23T17:14:18.363 回答
1

您是否在问如何确定远程机器选择使用的动态端口?没有自动化的方法可以做到这一点。服务器应该在两台机器都知道的端口上工作,或者你应该想办法让它们通过其他通信模式选择端口。通过连接到第三方服务器或托管客户端可以访问的 Web 服务。

于 2012-04-23T17:16:23.377 回答