VB .net : How can a Server handle multiple clients simultaneosly at an instance
I am facing a problem in VB .net Client/Server application where I am successfully able to talk between them using TCPListener and TCPClient class usage. However, when I try to connect another Client to the same server on the same welcome port, it errors out throwing an exception or behaves very unexpectedly.
- Isn't it true that the Server conn开发者_运维问答ection is on a WELCOME PORT for all the clients, and that each client connected gets a new port to carry on its communication with the server AUTOMATICALLY (according to the Tomcat webserver working)?
- OR, is the above statement untrue and that the APP program handle the connections manually?
Pls clarify with an example in VB .net, if possible?
The answer to your question is 'Yes it is true'. I do not have VB.NET code ready but you can have a look at C# code here C# sockets handling multiple clients.
Okay.. pasting my server code here for your comments... Pls pardon my ignorance in coding and teach me if I were wrong. Thanks.
The Client is more obvious... so dint paste it here.
Server:
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
When I try to connect a second client to this, the server drops the connection 1 and behaves unpredictably.
精彩评论