Named Pipes processing multiple messages - vb.net

I have a named pipes server running on a workstation. When the server receives a message I am able to process it. The problem is several messages can be sent at the same time. The server processes the first message but the remaining messages are lost. Not sure how to listen for multiple messages. I cannot batch the messages into one message as I need to have the server respond to each and every message separately. Does anyone know how I can accomplish this. My server code is below which is running in a thread.
Dim Pipe As New Pipes.NamedPipeServerStream("bellhop", Pipes.PipeDirection.InOut, -1, Pipes.PipeTransmissionMode.Message, Pipes.PipeOptions.Asynchronous)
While BellhopExiting = False
Pipe.WaitForConnection()
Dim Reader As New StreamReader(Pipe)
Dim XML As String = Reader.ReadLine
If XML IsNot Nothing Then
Dim Writer As New StreamWriter(Pipe)
Writer.AutoFlush = True
Try
ParseXML(XML)
'Send a success acknowledgement back to the sender.
Writer.WriteLine("Message Delivered")
Catch ex As Exception
'Send a failed acknowledgement back to the sender.
Writer.WriteLine("Failed->Bellhop->WaitForConnection->Computer: " & ComputerName & " Error: " & ex.Message)
End Try
End If
Pipe.Disconnect()
End While

Related

MSMQ FIFO/Synchronous Processing

I have a one threaded application. Its supposed to connect to a local MSMQ queue, and once a message is received it should process it before continuing to listen for additional messages. The messages contain data that is supposed to be inserted into a database table. But before inserting the data, it does a query to see if the item already exists. However, I am thinking that by creating a handler for ReceiveCompleted, that if more than one messages is in the queue that multiple threads are being spawned off. Is that what will happen? If it is then its possible that duplicate data could be in both messages, and my sql query may not see any duplication because the 2nd thread is still working and has not yet inserted its data into the database table.
Dim objQueue As New MessageQueue(ConfigurationManager.AppSettings("myQueuePath"))
AddHandler objQueue.ReceiveCompleted, AddressOf QueueReceived
objQueue.BeginReceive()
Private Sub QueueReceived(source As Object, asyncResult As ReceiveCompletedEventArgs)
Dim mq = DirectCast(source, MessageQueue)
Dim objMessage As Message = Nothing
Try
mq.Formatter = New XmlMessageFormatter(New [String]() {"System.String,mscorlib"})
objMessage = mq.EndReceive(asyncResult.AsyncResult)
Dim strMessage As String = objMessage.Body.ToString()
'Call routine to read data, check for suplicates and then insert into database
ProcessBXRS(objMessage)
Catch ex As Exception
'Do some exception handling
End Try
'Listen for next message
mq.BeginReceive()
End Sub
I guess I have to call BeginReceive() again.

vb.net WebClient.DownloadString fails with exception

I am working on a program in VS 2017 coding in VB.Net. The program downloads Web pages using Net.WebClient.DownloadString and then parses the data. It worked fine for a year or more then one day I started getting an exception when downloading the pages.
The ex.Message is: 'The underlying connection was closed: An unexpected error occurred on a send.'
The ex.InnerException.Message is: 'Unable to write data to the transport connection: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.'
I have VS 2017 installed on 2 other PC's at this location and on 1 at another location. They all continue to run the code without exception. It is only an issue on this PC.
The code is below (I changed the Web address but it fails for any valid URL).
Any ideas why this fails on my main PC only?
Public Function DownloadData() As Boolean
Dim strURL As String = "https://www.google.com/"
Dim strOutput As String
Try
Using WC As New Net.WebClient
strOutput = WC.DownloadString(strURL)
If strOutput.Length > 0 Then
If ParseData(strOutput) = True Then
Return True
End If
Else
Return False
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.InnerException.Message, "Error")
End Try
End Function

USB COM port data reading error

I am using people count device to read the InCount, Out Count record and it is connected with my PC COM3 USB port.. I have written the code to fetch the data, I am continuously receiving the below message while reading the data..... can I have some code or idea to fetch the record?
message is.... The operation has timed out.
mycode is below:
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim com1 As IO.Ports.SerialPort
'SerialPort sp = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.One);
Try
com1 = My.Computer.Ports.OpenSerialPort("COM3")
com1.BaudRate = 115200
com1.ReadTimeout = 10000
Do
Dim Incoming As String = com1.ReadLine()
If Incoming Is Nothing Then
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
Loop
Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If com1 IsNot Nothing Then com1.Close()
End Try
Return returnStr
End Function
You must know at least the following 7 parameter settings for the device you are trying to communicate with and set your serial port properties to match.
PortName
BaudRate
Parity
DataBits
StopBits
NewLine
Handshake
Some of these you might guess (Parity is usually none, Databits is usually 8 stop bits is usually 1, handshake is often none). But Hans is correct unless you get all these set properly you will never communicate with your device. Also it is better to open your serial port once during initialization of your program and then leave it open until the program closes.

How to properly handle disrupted TCP connection?

I'm using TCP socket connetion between a server program and a client program. Multiple client programs shall connect to the same port. The problem is that if I close a client program I get the following error on the server-program:
System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
http://i55.tinypic.com/nh135w.png
If I handle this by a try/catch, I am then not able to re-connect with the client-program, as it gives the following error (in the client program):
No connection could be made because the target machine actively refused it 127.0.0.1: 1234
Below is the listener code in the server program. I hope to get some help to understand how I can handle client program shutdown/restart&reconnect without the server program failing..
' This is the callback function for TcpClient.GetStream.Begin, It begins an asynchronous read from a stream.
Private Sub DoRead(ByVal aread As IAsyncResult)
Dim BytesRead As Integer
Dim strMessage As String
' Try
' Ensure that no other threads try to use the stream at the same time.
SyncLock _client.GetStream
' Finish asynchronous read into readBuffer and get number of bytes read.
If Client.Connected Then
BytesRead = _client.GetStream.EndRead(aread)
End If
End SyncLock
' Convert the byte array the message was saved into, minus one for the Chr(13) (carriage return).
strMessage = Encoding.ASCII.GetString(readBuffer, 0, BytesRead - 1)
ProcessIncoming(strMessage)
' Ensure that no other threads try to use the stream at the same time.
SyncLock Client.GetStream
' Start a new asynchronous read into readBuffer.
Client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf DoRead, Nothing)
End SyncLock
'Catch e As Exception
' ' This triggers if userlist is found empty
' ' Then gives problem, as it cant close the connection or something.. ??
' Debug.Print("UserConnection.DoRead Exception: " & e.ToString)
' CloseConnetion("Error: Stream Reciever Exception")
'End Try
End Sub
You don't. You're the server. You close the socket and forget about it. If the client wants more service it is up to him to reconnect.

VB IRC Client - writeStream only displays single word in IRC

Morning All,
I have been writing an ever so simple IRC client in visual basic. I have a niggly issue whereby when I am writing to the network stream. On other clients my message cuts off after the first space character. I'm sure this is something simple as the messages are being sent, receiving is fine and debugging the issue it wherever I read the message (i.e. if I debug.print the message being written to the stream it still includes all the words and spaces.) Here is my code.
Thanks in advance
'Send data to IRC Server
Sub Send(ByVal message)
Try
'Reformat message to IRC command
message = message & vbCrLf
Debug.Print(message)
'Convert message string into bytes
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(message)
'Write data to stream
ircStream.Write(sendBytes, 0, sendBytes.Length)
'Run test to see if the string sent matches the user input
Dim messageSent As String = Encoding.ASCII.GetString(sendBytes)
Debug.Print(messageSent)
'Display message on the screen( 0 = Sent Formatting )
PrintToScreen(message, 0)
Catch ex As Exception
'Catch error and display error message in the debug console
Debug.Print("Error Sending")
End Try
End Sub
You probably just need to prepend a ':' to your message like so...
PRIVMSG #chan_name :your message with spaces
By flushing, calling the flush function of the stream... Which (if I remember correctly) clears the data in the buffer, and writes it at the same time.
ircStream.Flush()