如何使用C#(套接字通信)检查TCP / IP端口可用性

时间:2014-06-17 10:47:17

标签: c#-4.0

我创建了一个使用TCP / IP套接字通信传输文件的应用程序。现在我想添加一项功能,检查特定端口号上的TCP / IP连接到远程服务器(无论是否可用于传输)。所以,请任何人帮助我。谢谢。

if(string.IsNullOrEmpty(txtIP.Text))                         返回;

if(string.IsNullOrEmpty(" 8001"))                         返回;

                int port;
                hostAddress = Dns.GetHostEntry(txtIP.Text).AddressList[0];
                int.TryParse("8001", out port);
                StateObject state = new StateObject();
                if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
                    state.workSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                else if (hostAddress.AddressFamily == AddressFamily.InterNetworkV6)
                    state.workSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);

                SocketAsyncEventArgs telnetSocketAsyncEventArgs = new SocketAsyncEventArgs();
                telnetSocketAsyncEventArgs.RemoteEndPoint = new IPEndPoint(hostAddress, port);
                telnetSocketAsyncEventArgs.Completed += new
                    EventHandler<SocketAsyncEventArgs>(telnetSocketAsyncEventArgs_Completed);

                state.workSocket.ConnectAsync(telnetSocketAsyncEventArgs)

private void telnetSocketAsyncEventArgs_Completed(object sender,SocketAsyncEventArgs e)         {             尝试             {                 if(e.SocketError == SocketError.Success)                 {                     if(e.LastOperation == SocketAsyncOperation.Connect)                     {                         MessageBox.Show(&#34;服务正在运行&#34;,hostAddress.ToString(),                             MessageBoxButtons.OK,MessageBoxIcon.Information);

                        ////send file if connection is established.
                    Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    byte[] fileName = Encoding.UTF8.GetBytes(m_fName); //file name
                    byte[] fileData = File.ReadAllBytes(txtFilePath.Text); //file
                    byte[] fileNameLen = BitConverter.GetBytes(fileName.Length); //lenght of file name
                    m_clientData = new byte[fileNameLen.Length + fileName.Length + fileData.Length];

                    fileNameLen.CopyTo(m_clientData, 0);
                    fileName.CopyTo(m_clientData, fileNameLen.Length);
                    fileData.CopyTo(m_clientData, fileNameLen.Length + fileName.Length);

                    //Code for Progress bar
                    lblmsg.Text = "";
                    double divider;
                    int extra;
                    fileProgress.Value = 0;
                    divider = (double)m_clientData.Length / 1024;
                    divider = Math.Ceiling(divider);
                    fileProgress.Maximum = m_clientData.Length;
                    int packet = 0;
                    for (int i = 0; i < divider; i++)
                    {
                        if (i == (divider - 1))
                        {
                            extra = (m_clientData.Length) - (i * 1024);
                            clientSock.Send(m_clientData, packet, extra, SocketFlags.None);
                        }
                        else
                        {
                            clientSock.Send(m_clientData, packet, 1024, SocketFlags.None);
                            packet = packet + 1024;
                            fileProgress.Value += 1024;
                        }
                    }
                    clientSock.Close();
                    fileProgress.Value = fileProgress.Maximum;
                    lblSender.Text = "File upload is completed.";
                    clientSocket.Disconnect(true);
                   // }

                }
            }
            else
            {
                bPortAvailble = false;
                MessageBox.Show("Service Is not Running", e.SocketError.ToString(),
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        catch (SocketException ex)
        {
            MessageBox.Show(ex.Message, "Service Is not Running",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }


}

1 个答案:

答案 0 :(得分:0)

您可以尝试使用TcpClient建立连接并捕获异常: TcpClient

在您使用Socket课程的情况下,请查看此处: Socket class。如果你没有先Send引用,那么Connect方法应该会失败:

  

如果您使用的是无连接协议,则必须在调用此方法之前调用Connect,否则Send将抛出SocketException。

首先使用Connect,并抓住它是否会抛出SocketExcpetion