I have an application which currently sends requests via TCP/IP Port 6000, and waits for a Reply.
I have been given the Request / Reply Protocol, but cant seem to send ASCII Control Characters like SOH,SOT,EOT etc... 01,02,03.
This is what I receive via TCP Port 6000 which I can display in the Msgbox.
Enquiry Message http://www.hcs-it.com/Enquiry.jpg
And this is what I am meant to send back ...
Enquiry Message http://www.hcs-it.com/Response.jpg
Here is my Class Code ...
Private Sub StartListen()
Try
' Must listen on correct port- must be same as port client wants to connect on.
Const portNumber As Integer = 6000
Dim tcpListener As New TcpListener(portNumber)
tcpListener.Start()
' Console.WriteLine("Waiting for connection...")
RichTextBox1.Text = RichTextBox1.Text & "Waiting for Connection ...." & vbCrLf
'
'
' SOH <ID> STX <DATA> ETX <CKSUM> EOT
'
'
Top:
'Accept the pending client connection and return a TcpClient initialized for communication.
Dim tcpClient1 As TcpClient = tcpListener.AcceptTcpClient()
' Get the stream
Dim networkStream As NetworkStream = tcpClient1.GetStream()
' Read the stream into a byte array
Dim bytes(tcpClient1.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient1.ReceiveBufferSize))
' Return the data received from the client to the console.
Dim clientdata As String = ASCIIEncoding.Unicode.GetString(bytes)
RichTextBox1.Text = RichTextBox1.Text & clientdata
Dim soh As String = GetChar(clientdata, 1)
Dim id As String = "010000000000000000"
Dim stx As String = GetChar(clientdata, 20)
Dim etx As String = GetChar(clientdata, 44)
Dim ack As String = System.Convert.ToChar(System.Convert.ToUInt32("06", 16))
Dim cksum As String = clientdata.Substring(44, 4)
Dim eot As String = GetChar(clientdata, 49)
Dim data As String = " 1Some Date "
Dim responseString As String = soh & id & stx & data & etx & cksum & eot & ack
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
networkStream.Write(sendBytes, 0, sendBytes.Length)
RichTextBox1.Text = RichTextBox1.Text & vbCrLf & responseString & vbCrLf
tcpClient1.Close()
tcpListener.Stop()
GoTo Top
Catch e As Exception
Console.WriteLine(e.ToString())
Console.ReadLine()
End Try
End Sub
ASCIIEncoding.Unicode you should investigate that expression... This is equivalent to Encoding.Unicode which is not what you want (you want ASCII).
Also, you are ignoring the return value from Read which is a common mistake.
Related
I'm trying to send about 250KBytes but I get cut at 8KBytes
I doesn't need any answer from the remote server.
I don't understand what I'm doing wrong.
Is like the tx doesn't change the outbuffer size.
Private Function SendReport7B(ByVal Msg As String, ByVal Host As String, ByVal Port As String) As String
Try
Dim Msgs() As String
Dim Tx As New TcpClient()
Dim stream As NetworkStream = Nothing
Dim LingerMode As New LingerOption(True, 1)
'Dim BSize As Integer
Tx.NoDelay = True
Tx.LingerState = LingerMode
Tx.SendTimeout = 5000
If Msg.Length > Tx.SendBufferSize Then
Tx.SendBufferSize = Msg.Length + 256
End If
Tx.Connect(Host, Port)
Msgs = Msg.Split(Chr(10))
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(Msg)
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
stream = Tx.GetStream()
'stream.WriteTimeout = 100
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
Tx.Close()
Return "OK" 'responseData
Catch ex As Exception
Return "Error: " & ex.Message
End Try
End Function
i am new to vb.net 2008 to get data from weigh scale using tcpclient(). below mentioned code is able to connect with machine but not getting the data. But hyperterminal is able to get data.
I searched most of the post but may coding exist only for serial port connection.
Output MsgBox :
Received: {0}
Imports System.Net.Sockets
Public Sub Connect(ByVal server As [String], ByVal _Ports As Int32, ByVal message As [String])
Try
' Create a TcpClient.
' Note, for this client to work you need to have a TcpServer
' connected to the same address as specified by the server, port
' combination.
Dim port As Int32 = _Ports
Dim client As New TcpClient()
'Dim client As New TcpClient(server, port)
client.Connect(server, port)
If client.Client.Connected Then TextBox3.Text = "Connected"
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
Dim stream As NetworkStream = client.GetStream()
Dim Buffer(client.ReceiveBufferSize) As Byte
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
'Console.WriteLine("Sent: {0}", message)
MsgBox("Sent: {0} " & message)
' Receive the TcpServer.response.
' Buffer to store the response bytes.
data = New [Byte](2047) {}
'MsgBox("Response Byte - " & data.Length)
' String to store the response ASCII representation.
Dim responseData As [String] = [String].Empty
' Read the first batch of the TcpServer response bytes.
Dim bytes As Int32 = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
'Console.WriteLine("Received: {0}", responseData)
MsgBox("Received: {0} " & responseData)
' Close everything.
stream.Close()
client.Close()
Catch e As ArgumentNullException
'Console.WriteLine("ArgumentNullException: {0}", e)
MsgBox("ArgumentNullException: {0}" & e.Message)
Catch e As SocketException
'Console.WriteLine("SocketException: {0}", e)
MsgBox("SocketException: {0}" & e.Message)
End Try
MsgBox("Got to this point in code")
'Console.WriteLine(ControlChars.Cr + " Press Enter to continue...")
'Console.Read()
End Sub
This:
MsgBox("Received: {0} " & responseData)
...does not automatically replace {0} with the value of responseData.
The {0} placeholder is used with the String.Format() function. Change your code to this, in all applicable places, and check the result:
' Let's also get rid of the legacy VB6 MsgBox() function:
MessageBox.Show(String.Format("Received: {0} ", responseData))
Also, what's with the square brackets around some data types (i.e. [String])? They aren't needed.
This is the code I have a problem on.
In my form load, I got this:
Dim port as new Ports.SerialPort("MyPort", 100000)
port.DataBits = 8
port.StopBits = Ports.StopBits.One
port.Parity = Ports.Parity.None
port.Open()
System.Threading.Thread.Sleep(200)
Then in my button1.Click event, I got this:
Try
If port.IsOpen Then
Dim inStream(80) As Byte
port.Read(inStream, 0, 80)
Dim returndata As String = System.Text.Encoding.ASCII.GetString(inStream, 0, 80)
returndata = returndata.Replace(Chr(2), "A")
returndata = returndata.Replace(Chr(3), "B")
msg("Data from Server : " + returndata)
Dim data As String
data = Write(TextBox2.Text, TextBox2.Text.Substring(0, 4))
Dim outStream As Byte() = _
System.Text.Encoding.ASCII.GetBytes(STX & data & ETX) '("Message from Client$")
ashsp.Write(outStream, 0, outStream.Length)
End If
Catch ex As Exception
End try
The problem here now is when I click button1, I got a TimeoutException when it hits port.Read(inStream, 0, 80).
Are you sure there are exactly 80 bytes to read? You could use the BytesToRead property to dynamically check how many bytes are available. Or if you are receiving only text on the serial port you could use the ReadExisting() method which puts all available bytes into a string object.
As much as there are many questions on here that are very similar, none of the supplied answers have helped me, which makes me sad :(
I've got a very large management system that I've been tasked to write some UDP packet sending/receiving for. I'd already written a prototype and all was well, so I started merging my code into said system. However, I've now got a (not show-stopping, but annoying) SocketException popping up:
System.Net.Sockets.SocketException occurred
ErrorCode=10048
Message=Only one usage of each socket address (protocol/network address/port) is normally permitted
NativeErrorCode=10048
Source=System
StackTrace:
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at System.Net.Sockets.UdpClient..ctor(Int32 port, AddressFamily family)
at System.Net.Sockets.UdpClient..ctor(Int32 port)
at Goose.Job.DeviceServerUDPReceiver.InitialiseReceiverClient() in C:\WORK\Trunk\GooseOrders\Classes\SheetCounter\DeviceServerUDPReceiver.vb:line 39
Here is the UDPReceiver class - Which is responsible for just sitting in a loop and waiting for responses from the Device Servers we've got dotted about the place.
Public Class DeviceServerUDPReceiver : Implements IDisposable
'///////////////////////////////////////////////////////////////////////////////
' CONSTANTS
'///////////////////////////////////////////////////////////////////////////////
Private Const TIBBO_DEVICE_REPLY_CMD_START As Integer = 0
Private Const TIBBO_DEVICE_REPLY_CMD_END As Integer = 3
Private Const TIBBO_MESSAGE_REPLY_DIVIDER As String = "_"
Private Const TIBBO_DEVICE_REPLY_OK As String = "OK"
'///////////////////////////////////////////////////////////////////////////////
' MEMBER VARIABLES
'///////////////////////////////////////////////////////////////////////////////
Public _ReceivingClient As System.Net.Sockets.UdpClient
Public _iReceivingPort As Integer = 2002
Public _thReceivingThread As System.Threading.Thread
Public _bClosing As Boolean
'///////////////////////////////////////////////////////////////////////////////
' EVENTS
'///////////////////////////////////////////////////////////////////////////////
Public Event GotDeviceResponse(ByVal sResponse As String)
Public Event FoundNewDevice(ByVal TibboObject As TibboDevice)
'///////////////////////////////////////////////////////////////////////////////
' METHODS
'///////////////////////////////////////////////////////////////////////////////
' Initialises the UDP receiver client on the specified port number. Then runs
' a listening thread constantly waiting to receive udp messages
Public Sub InitialiseReceiverClient()
Try
' TODO - FIX SOCKET EXCEPTION HERE - NOT THREAD ISSUE - THIS IS DUE TO
' THE SOCKET NOT BEING CLOSED. BUT SEEING HOW UDP IS CONNECTIONLESS .... ?!
_ReceivingClient = New System.Net.Sockets.UdpClient(_iReceivingPort)
Dim thStartThread As Threading.ThreadStart = New Threading.ThreadStart(AddressOf SitAndReceive)
_thReceivingThread = New Threading.Thread(thStartThread)
_thReceivingThread.IsBackground = True
_thReceivingThread.Start()
Catch ex As System.Net.Sockets.SocketException
Console.WriteLine("Socket Exception: " & ex.Message)
Finally
End Try
End Sub
' The endless loop listener thread. Will sit and wait for udp packets to
' process
Private Sub SitAndReceive()
Dim epEndPoint As System.Net.IPEndPoint = New System.Net.IPEndPoint(System.Net.IPAddress.Any, _iReceivingPort)
' infinite loop to listen for udp messages
While (_bClosing = False)
Try
Dim sMessage As String = ""
Dim byData() As Byte
byData = _ReceivingClient.Receive(epEndPoint)
sMessage = System.Text.Encoding.ASCII.GetString(byData)
Console.WriteLine(sMessage)
ProcessIncomingUDPDataMessage(sMessage)
Catch ex As System.Net.Sockets.SocketException
Console.WriteLine(ex.Message)
End Try
End While
End Sub
' close the connection to the receiving udp socket
Public Sub Close()
_bClosing = True
End Sub
' Processes incoming udp packets for answeres from the device servers
Private Sub ProcessIncomingUDPDataMessage(ByVal sMessage As String)
' UDP Data packet from Tibbo devices is set out as follows
'
' CMD_ANSWER
' Where "CMD" = The command the device is replying too and
' "ANSWER" = It's reply
Select Case sMessage.Substring(TIBBO_DEVICE_REPLY_CMD_START, TIBBO_DEVICE_REPLY_CMD_END)
Case TibboDevice.DEVICE_COMMAND_ATO
'/////////////////////////////////////////////////////////////////////////
' Any Tibbo's out there reply message
'/////////////////////////////////////////////////////////////////////////
Dim s() As String = sMessage.Split(TIBBO_MESSAGE_REPLY_DIVIDER)
Dim sMacAddress As String = s(2) ' the replying devices' mac address
Dim sIpAddress As System.Net.IPAddress = System.Net.IPAddress.Parse(s(3)) ' ip
Dim sNetBiosName As String = s(1) ' netbios name
Dim iTibboStatus As TibboDevice.ETIIBO_DEVICE_STATE = TibboDevice.ETIIBO_DEVICE_STATE.TIBBO_DEVICE_STATE_BAD ' status
' set this device status depending on the reply
If s(4) = TIBBO_DEVICE_REPLY_OK Then
iTibboStatus = TibboDevice.ETIIBO_DEVICE_STATE.TIBBO_DEVICE_STATE_OK
End If
' create a new tibbo device to pass back to the main form
Dim Tibbo As TibboDevice = New TibboDevice(sMacAddress, sIpAddress, sNetBiosName, iTibboStatus)
' raise event to add this to our list
RaiseEvent FoundNewDevice(Tibbo)
Case TibboDevice.DEVICE_COMMAND_STS
'//////////////////////////////////////////////////////////////////////////
' Status reply message
'//////////////////////////////////////////////////////////////////////////
Dim s() As String = sMessage.Split(TIBBO_MESSAGE_REPLY_DIVIDER)
Dim sResult As String = ""
' format our string nicely
sResult &= "Mac Address: " & vbTab & vbTab & s(1)
sResult &= Environment.NewLine & "IP Address: " & vbTab & vbTab & s(2)
sResult &= Environment.NewLine & "Device Name: " & vbTab & vbTab & s(3)
sResult &= Environment.NewLine & "TiOS FW: " & vbTab & vbTab & s(4)
sResult &= Environment.NewLine & "Goose SC FW: " & vbTab & vbTab & s(5)
sResult &= Environment.NewLine & "System Uptime: " & vbTab & vbTab & s(6)
sResult &= Environment.NewLine & "System Time: " & vbTab & vbTab & s(7)
sResult &= Environment.NewLine & "System Status: " & vbTab & vbTab & s(8)
RaiseEvent GotDeviceResponse(sResult)
Case TibboDevice.DEVICE_COMMAND_ASC
'////////////////////////////////////////////////////////////////////////////
' Average sheet count message
'////////////////////////////////////////////////////////////////////////////
Dim s() As String = sMessage.Split(TIBBO_MESSAGE_REPLY_DIVIDER)
Dim sResult As String = ""
RaiseEvent GotDeviceResponse(sResult)
Case TibboDevice.DEVICE_COMMAND_NAM
'////////////////////////////////////////////////////////////////////////////
' Changed device name reply message
' Device will reply NAM_[NEWNAME] - once it's set it's new name
'////////////////////////////////////////////////////////////////////////////
Dim s() As String = sMessage.Split(TIBBO_MESSAGE_REPLY_DIVIDER)
Dim sResult As String = ""
RaiseEvent GotDeviceResponse(sResult)
Case TibboDevice.DEVICE_COMMAND_IDX
'////////////////////////////////////////////////////////////////////////////
' Device responds with it's device id
'////////////////////////////////////////////////////////////////////////////
Dim s() As String = sMessage.Split(TIBBO_MESSAGE_REPLY_DIVIDER)
Dim sResult As String = ""
' TODO - do something with the result
Case TibboDevice.DEVICE_COMMAND_RBT
'////////////////////////////////////////////////////////////////////////////
' Device is going down for a reboot - not much to do here, we have to wait
'////////////////////////////////////////////////////////////////////////////
Case TibboDevice.DEVICE_COMMAND_BUZ
'////////////////////////////////////////////////////////////////////////////
' Device has played it's buzz sound - ignore
'////////////////////////////////////////////////////////////////////////////
Case TibboDevice.DEVICE_COMMAND_FSH
'////////////////////////////////////////////////////////////////////////////
' Device flashed it's LEDs - ignore
'////////////////////////////////////////////////////////////////////////////
Case TibboDevice.DEVICE_COMMAND_AIP
'////////////////////////////////////////////////////////////////////////////
' Device replies with it's actual ip address
'////////////////////////////////////////////////////////////////////////////
Dim s() As String = sMessage.Split(TIBBO_MESSAGE_REPLY_DIVIDER)
Dim sResult As String = ""
' TODO - do something with the result
Case TibboDevice.DEVICE_COMMAND_CBC
'////////////////////////////////////////////////////////////////////////////
' Device replies with it's current box count
'////////////////////////////////////////////////////////////////////////////
Dim s() As String = sMessage.Split(TIBBO_MESSAGE_REPLY_DIVIDER)
Dim sResult As String = ""
' TODO - do something with the result
Case TibboDevice.DEVICE_COMMAND_STP
'////////////////////////////////////////////////////////////////////////////
' Device has been stopped - won't reply. Only way to bring it back to life
' is to press the 'reset' button on the actual unit - ignore
'////////////////////////////////////////////////////////////////////////////
End Select
End Sub
Protected Overridable Overloads Sub Dispose(disposing As Boolean)
If (disposing) Then
' free managed objects
'_ReceivingClient = Nothing
_bClosing = True
End If
End Sub
Public Overloads Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
End Class
Now, all I'm doing in the main form, is: When my listener form is closed - I want to close the listener down (obviously)... For this, I'm using Dispose(). However, when someone wants to start it up again, said exception occurs on the byData = _ReceivingClient.Receive(epEndPoint) line in the SitAndReceive procedure.
Since UDP is transaction based and its sockets (possibly theoretically) can't be in a CLOSE_WAIT state, what is stopping me from closing it down and then immediately relaunching the listener?
I must admit I'm new to UDP sockets, so far however, I've found them a joy to work with and even though this exception wouldn't crash an end-users software (with a simple try/catch), it does have me intrigued and I'd like to understand why it's happening.
Any help is very much appreciated.
Managed to figure this out in the end. Apparently if you want to have more than one connection to a socket, you have to manually configure it, like so:
Dim endPoint = New System.Net.IPEndPoint(0, _iReceivingPort)
_ReceivingClient = New System.Net.Sockets.UdpClient()
_ReceivingClient.ExclusiveAddressUse = False
_ReceivingClient.Client.SetSocketOption(Net.Sockets.SocketOptionLevel.Socket, Net.Sockets.SocketOptionName.ReuseAddress, True)
_ReceivingClient.Client.Bind(endPoint)
Works now, so I'm happy.
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 connection 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.