vb TCP client application breaks trying to read server response - vb.net

Can anyone tell me why my code freezes up at "Return sockReader.ReadLine()"? Thank you. I'm trying to get information back from my Raspberry Pi server when I send a command using "Public Sub Send" and the code is getting stuck.
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Public Class TCPControl
Public sock As TcpClient
Public DataStream As StreamWriter
Public DataGet As TcpListener
Private netStream As NetworkStream
Private sockReader As StreamReader
Public Sub New(Host As String, Port As Integer)
' CLIENT
sock = New TcpClient(Host, Port)
netStream = sock.GetStream()
sockReader = New StreamReader(netStream)
DataStream = New StreamWriter(sock.GetStream)
Dim localAddr As IPAddress = IPAddress.Parse("172.16.2.104")
DataGet = New TcpListener(localAddr, 6969)
End Sub
Public Sub Send(Data As String)
DataStream.Write(Data & vbCrLf)
DataStream.Flush()
End Sub
Public Function Receive()
Dim howMany As Integer = sock.Available()
If netStream.DataAvailable Then
Return sockReader.ReadLine()
End If
Return howMany
End Function
End Class

Related

Error while starting the server in a server-client program

Im working on a server-client program in Visual Studio 2015. Here im getting an error saying that the socketException was unhandled. The error is near 'Server.Start()'. The rest of the code is not displaying any error hence didnt post it.
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Public Class TCPControl
Public Event MessageReceived(sender As TCPControl, Data As String)
' SERVER CONFIG
Public ServerIP As IPAddress = IPAddress.Parse("10.0.0.253")
Public ServerPort As Integer = 64555
Public Server As TcpListener
Private CommThread As Thread
Public IsListening As Boolean = True
' CLIENTS
Private Client As TcpClient
Private ClientData As StreamReader
Public Sub New()
Server = New TcpListener(ServerIP, ServerPort)
Server.Start()
CommThread = New Thread(New ThreadStart(AddressOf Listening))
CommThread.Start()
End Sub

Simple VB.Net text base communication server

I try for one week to provide a PHP application (client) and a VB.Net application (server) via text messages (JSON).
I must therefore open a socket server in VB.Net, read the client message and close the connection. Of course by managing connections from clients in separate threads since PHP may well send multiple queries simultaneously.
This is a trivial task in Java, as I usually do, but and a VB.Net I tried many solutions found on StackOverflow and CodeProject, but none is exactly what I want to achieve .
Finally I think I found something interesting !
Based on the post Writing a Simple HTTP Server in VB.Net from Patrick Santry, I have a functional class :
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Public Class Server
#Region "Declarations"
Private Shared singleServer As Server
Private Shared blnFlag As Boolean
Private LocalTCPListener As TcpListener
Private LocalPort As Integer
Private LocalAddress As IPAddress = GetIPAddress()
Private ServerThread As Thread
#End Region
#Region "Properties"
Public Property ListenPort() As Integer
Get
Return LocalPort
End Get
Set(ByVal Value As Integer)
LocalPort = Value
End Set
End Property
Public ReadOnly Property ListenIPAddress() As IPAddress
Get
Return LocalAddress
End Get
End Property
#End Region
#Region "Methods"
Private Function GetIPAddress() As IPAddress
With System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName())
If .AddressList.Length > 0 Then
Return New IPAddress(.AddressList.GetLowerBound(0))
End If
End With
Return Nothing
End Function
Friend Shared Function getServer(ByVal LocalPort As Integer, ByVal Optional LocalAddress As String = Nothing) As Server
If Not blnFlag Then
singleServer = New Server
If Not LocalAddress Is Nothing Then
Server.singleServer.LocalAddress = IPAddress.Parse(LocalAddress)
End If
If Not LocalPort = 0 Then
Server.singleServer.LocalPort = LocalPort
End If
blnFlag = True
Return Server.singleServer
Else
Return Server.singleServer
End If
End Function
Public Sub StartServer()
Try
LocalTCPListener = New TcpListener(LocalAddress, LocalPort)
LocalTCPListener.Start()
ServerThread = New Thread(AddressOf StartListen)
serverThread.Start()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
Public Overloads Sub SendResponse(ByVal sData As String, ByRef thisSocket As Socket)
SendResponse(Encoding.UTF8.GetBytes(sData), thisSocket)
End Sub
Public Overloads Sub SendResponse(ByVal bSendData As [Byte](), ByRef thisSocket As Socket)
Dim iNumBytes As Integer = 0
If thisSocket.Connected Then
If (iNumBytes = thisSocket.Send(bSendData, bSendData.Length, 0)) = -1 Then
' socket error can't send packet
Else
' number of bytes sent.
End If
Else
' connection dropped.
End If
End Sub
Private Sub New()
' create a singleton
End Sub
Private Sub StartListen()
Do While True
' accept new socket connection
Dim mySocket As Socket = LocalTCPListener.AcceptSocket
If mySocket.Connected Then
Dim ClientThread As Thread = New Thread(Sub() Me.ProcessRequest(mySocket))
ClientThread.Start()
End If
Loop
End Sub
Private Sub ProcessRequest(ByRef mySocket As Socket)
Dim bReceive() As Byte = New [Byte](1024) {}
Dim i As Integer = mySocket.Receive(bReceive, bReceive.Length, 0)
Dim sRequest = Encoding.UTF8.GetString(bReceive)
Dim sResponse As String
sResponse = "Your message was : " & sRequest
SendResponse(sResponse, mySocket)
mySocket.Close()
End Sub
Public Sub StopServer()
Try
LocalTCPListener.Stop()
ServerThread.Abort()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
#End Region
End Class
It remains for me to process the request and generate the response in the processRequest method.

referencing a dll in a windows service

I wrote an OPC client using interop.opcautomation.dll. I wrote it as a windows form in vb 2010 express. everything is currently working well. I wanted to make it a windows service though. The problem I am having is that it will not connect to the opc server when I run the service. I get the following exception "Object reference not set to an instance of an object.- OPC Connect Error" I get the exception at the end of the code where I am trying to connect. Below is the code. Thanks for any input, it is appreciated.
Imports System.ServiceProcess
Imports System.Threading
Imports System.Text
Imports System.Windows.Forms
Imports System
Imports System.IO
Imports System.IO.File
Imports System.Net
Imports OPCAutomation
Public Class Service1
Inherits System.ServiceProcess.ServiceBase
Dim WithEvents OPCServer As OPCAutomation.OPCServer
Dim WithEvents ConnectedGroup As OPCAutomation.OPCGroup
Dim Batch As String
Dim Group As String
Dim Press As String
Dim Line As String
Dim sWidth As String
Dim sHeight As String
Dim sBifold As String
Dim sCore As String
Dim StartUp As Integer
Dim iHandle As Integer
Dim sError As String
Dim ItemIds(60) As String
Dim ServerHandles As Array
Dim ClientHandles(60) As Integer
Dim ServerErrors As Array
Dim SnapServerURL As String = "snapserver"
Private trd As Thread
Private Stopping As Boolean = False
Private StoppedEvent As New ManualResetEvent(False)
Protected Overrides Sub OnStart(ByVal args() As String)
EventLog.WriteEntry("PressControlService in OnStart.")
trd = New Thread(AddressOf ServiceMain)
trd.IsBackground = True
trd.Start()
End Sub
Protected Overrides Sub OnStop()
EventLog.WriteEntry("PressControlService in OnStop.")
Me.Stopping = True
Me.StoppedEvent.WaitOne()
End Sub
Private Sub ServiceMain()
Dim strOPCServerName As String
Dim strOPCServerNode As String
Dim strOPCGroupName As String
Dim i As Integer
StartUp = 0
strOPCServerName = "Kepware.KEPServerEX.V5"
strOPCServerNode = ""
strOPCGroupName = "MyGroup"
Try
Dim OPCServer As New OPCAutomation.OPCServer
Catch ex As Exception
EventLog.WriteEntry(ex.Message & " - New OPC Server")
End Try
Try
OPCServer.Connect(strOPCServerName, strOPCServerNode)
Catch ex As Exception
EventLog.WriteEntry(ex.Message & "- OPC Connect Error")
End Try
End Sub
End Class

VB.net TCPListner windows service

I'm trying to build a windows service tcpip server to install on some computer to be able to send messages to them...
The following code is working perfectly if I run it as a normal windows application but if I use it to create a windows service it doesn't run as expected.
Throught the Visual studio "attach debug" I can see the debug and every time I send a request from the client I see this:
The thread 0xf34 has exited with code 259 (0x103).
That means the thread was entered but no output, or console.write...
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Public Class Main
Private serverSocket As TcpListener
Private Delegate Sub WriteMessageDelegate(ByVal msg As String)
Dim listenThread As New Thread(New ThreadStart(AddressOf ListenForClients))
Private Sub ListenForClients()
serverSocket = New TcpListener(IPAddress.Any, 11000)
serverSocket.Start()
Console.WriteLine("Listen for clients...")
While True 'blocks until a client has connected to the server
Dim client As TcpClient = Me.serverSocket.AcceptTcpClient()
Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf HandleClientComm))
clientThread.Start(client)
End While
End Sub
Private Sub HandleClientComm(ByVal client As Object)
Dim tcpClient As TcpClient = DirectCast(client, TcpClient)
Dim clientStream As NetworkStream = tcpClient.GetStream()
Dim message As Byte() = New Byte(4095) {}
Dim bytesRead As Integer
Console.WriteLine("Handle client comm...")
While True
bytesRead = 0
bytesRead = clientStream.Read(message, 0, 4096) 'blocks until a client sends a message
If bytesRead = 0 Then
Exit While 'the client has disconnected from the server
End If
'message has successfully been received
'Dim encoder As New ASCIIEncoding()
'Dim serverResponse As String = "Response to send"
'Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(serverResponse)
'clientStream.Write(sendBytes, 0, sendBytes.Length)
Console.WriteLine(bytesRead)
'message has successfully been received
Dim encoder As New ASCIIEncoding()
' Convert the Bytes received to a string and display it on the Server Screen
Dim msg As String = encoder.GetString(message, 0, bytesRead)
Console.WriteLine(msg)
'WriteMessage(msg)
End While
tcpClient.Close()
End Sub
Private Function BytesToString(
ByVal bytes() As Byte) As String
Return Encoding.Default.GetString(bytes)
End Function
Private Sub WriteMessage(ByVal msg As String)
If Me.MessagesLog.InvokeRequired Then
Dim d As New WriteMessageDelegate(AddressOf WriteMessage)
Me.MessagesLog.Invoke(d, New Object() {msg})
Else
Me.MessagesLog.AppendText(msg & Environment.NewLine)
End If
End Sub
Protected Overrides Sub OnStart(ByVal args() As String)
listenThread.Start()
Console.WriteLine("Starting...")
End Sub
Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
'listenThread.Abort()
End Sub
End Class
Can someone help me?
Found the problem...
Windows services dont do output to console.write()... it has to be with debug.print()
"The Thread..." output is normal..
Thank you,
AP

UDPclient buffer too small

Hello to all I am developing an application that needs to send a image via the UDP socket.I know that TCP is a better protocol,but playing with Kryonet in Java I have learnt that UDP is better for this type of application.I have this small class that I have made:
Imports System.Net.Sockets
Imports System.Net
Imports System.Text.Encoding
Public Class BasicUDPClient
Event ClientMessageReceived(ByVal msg() As Byte)
Public Property HostName As String = "localhost"
Public Property Port As Integer = 8991
Dim sender As New UdpClient(0)
Dim receiver As New UdpClient(Port)
Dim th_recv As New Threading.Thread(AddressOf Receive)
Dim run As Boolean
Dim ep As New IPEndPoint(System.Net.IPAddress.Any, 0)
Public Sub New(ByVal host As String, ByVal port As Integer)
HostName = host
Me.Port = port
receiver.Client.Blocking = False
'10485760 = 10MB
receiver.Client.ReceiveBufferSize = 10485760
sender.Client.SendBufferSize = 10485760
receiver.Client.ReceiveTimeout = 5000
StartReceive()
End Sub
Public Sub SendString(ByVal msg As String)
SendMessage(UTF8.GetBytes(msg))
End Sub
Public Sub SendMessage(ByVal msg() As Byte)
sender.Connect(HostName, Port)
sender.Send(msg, msg.Length)
End Sub
Public Sub StartReceive()
run = True
th_recv = New Threading.Thread(AddressOf Receive)
th_recv.Start()
End Sub
Public Sub StopReceive()
run = False
End Sub
Private Sub Receive()
While (run)
Try
RaiseEvent ClientMessageReceived(receiver.Receive(ep))
Catch ex As Exception
Debug.WriteLine("Error: " & ex.Message)
End Try
End While
End Sub
End Class
It works great with string likes hello,but when I am sending the image,about 200000-150000 bytes I got an error saying that the buffer is lower than the contents of the packet (I can post an image of the error message,but my .net language is in Spanish)
Thanks
With UDP you cannot send messages bigger than 64KB. Use TCP, or split the payload yourself into multiple messages which will be extremely complex because messages can be lost.
ReceiveBufferSize is not what you think it is. It almost never helps to use it.
Code for sender and receiver is missing but sender.Connect looks strange given that UDP is connectionless.