代码之家  ›  专栏  ›  技术社区  ›  Jonno

.NET VB如何让服务器侦听多个端口?

  •  4
  • Jonno  · 技术社区  · 16 年前

    我正在写一个非常小和简单的服务器,我想在多个端口上监听它。

    我正在使用下面的内容,但无法接受与端口8081的连接-有没有建议我做错了什么?

    (我实际上想监听多个端口,我不会混淆多个连接)

    Public Sub StartServer()
    
        Dim ports() As Integer = {8080, 8081}
        Dim portList As String = ""
    
    
    
        Dim address As IPAddress = IPAddress.Any
    
        ' map the end point with IP Address and Port
        'Create Endpoints
        Dim EndPoints(ports.Length) As IPEndPoint
    
        'Create sockets
        Dim Sockets(ports.Length) As Socket
    
        Dim i As Integer = 0
        For i = 0 To ports.Length - 1
            portList = portList & ports(i) & " : "
            EndPoints(i) = New IPEndPoint(address, ports(i))
            Sockets(i) = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            Sockets(i).Bind(EndPoints(i))
            Sockets(i).Listen(20)
    
            Log("Listening on: All ips &  Port: " & ports(i))
    
    
        Next
    
        Log("Listening on: All ips &  Ports: " & portList)
    
    
    
        Do While Not Me.DoStop
            ' Wait for an incoming connections
            For i = 0 To ports.Length - 1
                Dim sock As Socket = Sockets(i).Accept()
    
    
                ' Connection accepted
    
                ' Initialise the Server class
                Dim ServerRun As New Server(sock)
    
                ' Create a new thread to handle the connection
                Dim t As Thread = New Thread(AddressOf ServerRun.HandleConnection)
    
    
                t.IsBackground = True
                t.Priority = ThreadPriority.BelowNormal
                t.Start()
            Next
    
            ' Loop and wait for more connections
        Loop
    
    End Sub
    
    1 回复  |  直到 16 年前
        1
  •  3
  •   Chris Diver    16 年前

    同步法 Sockets(i).Accept 将阻止,直到它接收到连接。在第一个套接字上建立连接之前,不会在第二个套接字上调用accept方法。

    我认为您想要实现异步套接字,在 http://msdn.microsoft.com/en-us/library/fx6588te.aspx

    数组也是一个元素太长。

    Dim EndPoints(ports.Length - 1) As IPEndPoint