-1

谁能分享一个简单的VB 2008代码来打开一个端口。我希望它就像utorrent一样如何更改数据传输的侦听端口。如果你能帮助我,非常感谢!

4

2 回答 2

2

正如 Avner 所指出的,uTorrent不是简单的代码。如果你想在那个级别上做任何事情,那么你有很多事情要做。

这是一个可以构建的简单示例套接字程序。

Imports System.Net
Imports System.Net.Sockets

Module Module1

    Sub Main()
        Console.WriteLine("Enter the host name or IP Address to connect to:")
        Dim hostName = Console.ReadLine().Trim()
        If hostName.Length = 0 Then
            ' use the local computer if there is no host provided
            hostName = Dns.GetHostName()
        End If

        Dim ipAddress As IPAddress = Nothing
        ' parse and select the first IPv4 address
        For Each address In Dns.GetHostEntry(hostName).AddressList
            If (address.AddressFamily = AddressFamily.InterNetwork) Then
                ipAddress = address
                Exit For
            End If
        Next

        ' you will have to check beyond this point to ensure
        ' there is a valid address before connecting

        Dim client = New TcpClient()
        Try
            ' attempt to connect on the address
            client.Connect(ipAddress, 80)

            ' do whatever you want with the connection


        Catch ex As SocketException
            ' error accessing the socket
        Catch ex As ArgumentNullException
            ' address is null
            ' hopefully this will never happen
        Catch ex As ArgumentOutOfRangeException
            ' port must be from 0 to 64k (&HFFFF)
            ' check and ensure you've used the right port
        Catch ex As ObjectDisposedException
            ' the tcpClient has been disposed
            ' hopefully this will never happen
        Catch ex As Exception
            ' any other exception I haven't dreamt of

        Finally
            ' close the connection

            ' the TcpClient.Close() method does not actually close the
            ' underlying connection. You have to close it yourself.
            ' http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B821625
            client.GetStream().Close()

            ' then close the client's connection
            client.Close()
        End Try
    End Sub

End Module

请注意,套接字编程非常复杂,您必须针对所有边缘情况彻底测试您的代码。

祝你好运!

于 2013-09-20T07:34:16.713 回答
1

uTorrent 绝非“简单代码”。这是一个复杂的应用程序,除了打开一个端口并将位推入和推出之外,还有很多网络逻辑在进行。

但是低级通信处理的起点是System.Net.Sockets包含Socket类的命名空间。它允许低级控制,例如打开端口、侦听连接并自己处理它们。

这是关于 VB.NET 中的 Socket 编程的教程,但是如果您搜索“C# Socket 教程”,您可能会找到更多信息。C# 语法与 VB.NET 有点不同,但它使用相同的类和相同的概念,因此您可能能够将这些课程应用到您自己的代码中。

于 2013-09-20T07:02:34.733 回答