VB .net:服务器如何在一个实例上同时处理多个客户端

时间:2011-09-22 18:21:58

标签: vb.net multithreading client-server

我在VB .net客户端/服务器应用程序中遇到问题,我可以使用TCPListener和TCPClient类使用它们成功地在它们之间进行通信。但是,当我尝试将另一个客户端连接到同一个欢迎端口上的同一服务器时,它会导致抛出异常或行为非常意外。

  • 服务器连接是否在所有客户端的WELCOME PORT上,并且每个连接的客户端都有一个新端口与服务器AUTOMATICALLY进行通信(根据Tomcat网络服务器的工作情况)是不是真的? / LI>
  • OR,上述语句是不真实的,APP程序是否手动处理连接?

如果可能,请用VB .net中的示例澄清一下?

2 个答案:

答案 0 :(得分:1)

你问题的答案是“是的,这是真的”。我没有准备好VB.NET代码,但您可以在这里查看C#代码C# sockets handling multiple clients

答案 1 :(得分:0)

好的..在这里粘贴我的服务器代码以征求您的意见......请原谅我对编码的无知,如果我错了就教我。感谢。

客户端更明显......所以在这里粘贴它。

服务器

Public Class ServerSide2

...other stuff...

Public Class Packet

    Public packetType As String = "Data"
    Public packetOwnerIPAddress As String
    Public packetOwnerPort As String
    Public content As String

    Public Sub New(ByVal type As String, ByVal ip As String, ByVal port As String, ByVal data As String)

        packetType = type
        packetOwnerIPAddress = ip
        packetOwnerPort = port
        content = data

    End Sub
End Class

Public Class Worker

    Dim myLogger As Logger

    Dim name As String

    Dim ipClientAddress As IPAddress    'Client's IP address
    Dim ipClientPort As Integer = 22222 'Client listening on this port

    Dim tcpServer As TcpListener
    Dim tcpClient As TcpClient
    Dim networkStream As NetworkStream

    Dim readSize As Integer = 100

    Public Sub New(ByRef logger As Logger, ByVal id As String)

        myLogger = logger
        name = id

        myLogger.Trace("A new Worker object has been created for client: {0}", ipClientAddress)

    End Sub

    'Listener code
    Public Sub runClientHandler(ByVal ar As IAsyncResult)
        'code to listen to independent client
        Dim clientdata As String
        Dim numBytesRead As Integer = 0

        Thread.CurrentThread.Priority = ThreadPriority.Highest

        ' Get the listener that handles the client request.
        Dim listener As TcpListener = CType(ar.AsyncState, TcpListener)

        ' End the operation and display the received data on
        ' the console.
        tcpClient = listener.EndAcceptTcpClient(ar)

        ' Process the connection here. (Add the client to a
        ' server table, read data, etc.)
        myLogger.Info("Client connected completed")

        ' Signal the calling thread to continue.
        tcpClientConnected.Set()

        networkStream = tcpClient.GetStream()

        Dim ipEndPoint As IPEndPoint = tcpClient.Client.RemoteEndPoint
        ipClientAddress = ipEndPoint.Address

        myLogger.Info("A new Worker thread has been started.")

        While Not stopping

            myLogger.Trace("Start looping.")

            Dim bytes(readSize) As Byte

            numBytesRead = networkStream.Read(bytes, 0, bytes.Length)
            clientdata = Encoding.ASCII.GetString(bytes, 0, numBytesRead)

            'check for validity of the data
            If numBytesRead = 0 Then
                'connection lost
                myLogger.Trace("No data read.")
                Exit While
            End If

            If clientdata.Contains("SampleTest : {") Then

                'Message box the client data
                MsgBox("Test data from Client = " + clientdata)

                myLogger.Trace("Test data from Client = " + clientdata)

            ElseIf clientdata.Contains("Recieve Port : ") Then

                'Heed to Client's request on the port number server should reply
                Dim dest(5) As Char
                Dim destString As String = ""

                clientdata.CopyTo(15, dest, 0, clientdata.Length - 15)

                ipClientPort = CInt(CStr(dest))

                myLogger.Trace("Client Waiting on Port# : " + CStr(dest) + "for sorted packets.")

                'MsgBox("Client Waiting on Port# : " + CStr(dest))
            ElseIf clientdata.Contains("Packet Size : ") Then

                Dim dest(5) As Char
                Dim destString As String = ""
                clientdata.CopyTo(14, dest, 0, clientdata.Length - 14)

                readSize = CInt(CStr(dest))

                myLogger.Trace("Client's communicated Packet Size : " + CStr(dest))

            Else

                myLogger.Info("Begin to queue Data Packets.")

                While True

                    myLogger.Info("Data Packet.")

                    SyncLock Stats.locker

                        myLogger.Info("Got the lock.")

                        Stats.queueLength = Stats.requestQueue.Count

                        If Stats.queueLength < Stats.MAX_QUEUE_LENGTH Then
                            'Queue has some space to fit more packets

                            myLogger.Info("Queue has some space for this packet.")

                            Stats.packetNum = Stats.packetNum + 1
                            Dim newPacket As Packet = New Packet("Data", ipClientAddress.ToString, ipClientPort, clientdata)

                            Stats.requestQueue.Enqueue(newPacket)

                            Stats.sumQueueLength = Stats.sumQueueLength + Stats.requestQueue.Count
                            Stats.meanQueueLength = Stats.sumQueueLength / Stats.packetNum

                            myLogger.Info("Stats :: Packet #: {0}, QueueLength: {1}, MeanQueueLength: {2}.", Stats.packetNum, Stats.requestQueue.Count, Stats.meanQueueLength)
                        Else
                            'Queue is FULL, Ignore the packet
                            Stats.numDropPackets = Stats.numDropPackets + 1
                            myLogger.Info("Stats :: Dropped Packets: {0}.", Stats.numDropPackets)
                        End If

                    End SyncLock

                    numBytesRead = networkStream.Read(bytes, 0, bytes.Length)
                    clientdata = Encoding.ASCII.GetString(bytes, 0, numBytesRead)

                    'check for validity of the data
                    If numBytesRead = 0 Then
                        'connection lost
                        myLogger.Trace("No data read.")
                        Exit Sub
                    End If

                End While

            End If

        End While

        myLogger.Trace("End looping.")

    End Sub

End Class

Sub ListeningThread()
    Dim count As Integer = 0

    tcpServer = New TcpListener(ipAddress, iPort)
    tcpServer.Start()

    Try
        While Not stopping And count < Stats.MAX_CLIENTS

            count = count + 1
            Dim workerName = "worker:" + CStr(count)
            Dim worker As Worker = New Worker(logger, workerName)

            logger.Info("Waiting for a client to connect")
            DoBeginAcceptTcpClient(worker, tcpServer)

            logger.Info("Connected to {0}.", workerName)

            'Add the client to the hashTable
            'ADITYA later clients.Add(workerName, client)

            If SortAndSendThrd Is Nothing Then
                'Start a new thread
                SortAndSendThrd = New Thread(SortAndSendThrdStart)
                SortAndSendThrd.Priority = ThreadPriority.Highest
            End If

            If Not SortAndSendThrd.IsAlive Then
                SortAndSendThrd.Start()
                logger.Debug("Started off a Sort thread")
            End If

            'Dim i As Integer = 0
            'Dim objValue As Object

            'For Each objKey In clients.Keys
            '    objValue = clients.Item(objKey)
            '    'MsgBox("[" & objKey.ToString & ", " & objValue.ToString & "]")
            'Next objKey

        End While
    Catch ex As IOException
        ToolStripStatusLabel1.Text = "ERROR : SocketException: {0}" + ex.Message
        'MsgBox(ex.Message + ":::2")
    Catch ex As SocketException
        ToolStripStatusLabel1.Text = "ERROR : SocketException: {0}" + ex.Message
        'MsgBox(ex.Message + ":::1")
    End Try

    'tcpServer.Stop()
    'client.Close()

    logger.Debug("The Server's listening handler has come to an end.")

End Sub
End Class

当我尝试将第二个客户端连接到此时,服务器会断开连接1并且行为不可预测。