VB.net TCPListner windows service - vb.net

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

Related

vb TCP client application breaks trying to read server response

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

Use a Dictionary between different thread in VB.NET

I am working on a project that have a server, whenever a clients connects it stores its user_id, ip in the dictionary which i have used. When I store the information between the different threads it is working but when I try to access the dictionary from different threads, it's not working well.
Let me clear what my code should do: There is one main thread active and listening for clients, when a clients wants to connect, main thread creates a child thread and that thread gets connected with client, client sends it a user_id, this user_id (as key for dictionary) and Tcpclient (as Value) get stored in dictionary. Further one client sends a message for particular client to server, that message contains the user_id for receiver. Now this client is connected with a particular thread which will check the key(user_id) in dictionary and then send the data to that client but dictionary is not giving the correct value for connected clients it just returns false even that client is connected.
Below is my code example.
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.IO
Public Class Mainform
Dim _server As TcpListener
Dim _listOfClients As New Dictionary(Of String, TcpClient)
Public MessageQueue As New Dictionary(Of String, Queue(Of String))
'Dim ClientData As StreamReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim port As Integer = 8888
_server = New TcpListener(System.Net.IPAddress.Any, port)
_server.Start()
Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub NewClient()
Dim client As TcpClient = _server.AcceptTcpClient()
Dim toRec(100000) As Byte
Dim nss As NetworkStream = client.GetStream()
nss.Read(toRec, 0, toRec.Length)
Dim ClientData As String = Encoding.ASCII.GetString(toRec)
MsgBox("Client Connected: " & ClientData)
Dim too() As String
Dim status As Boolean = False
Dim sendto As String
Try
_listOfClients.Add(ClientData, client)
Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient)
While True
Dim thisClient As String = ClientData
Dim ns As NetworkStream = client.GetStream()
Dim toRecieve(100000) As Byte
ns.Read(toRecieve, 0, toRecieve.Length)
Dim txt As String = Encoding.ASCII.GetString(toRecieve)
'MsgBox(txt)
too = txt.Split("#") 'server receives data in single string where user_id and message is connected with '#'
sendto = String.Copy(too(0)) 'this is the user_id of receiver client
If _listofclients.ContainsKey(sendto) Then
Dim data As String
data = String.Join("#", too)
Dim buffer As Byte() = Encoding.ASCII.GetBytes(data)
Dim nets As NetworkStream = _listofclients(sendto).GetStream()
nets.Write(buffer, 0, buffer.Length)
End If
End While
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class

Sending Files over IpV6

I want to send a file over the internet with a tcp connection. My code handles this for IpV4 well (creddits here go to http://technotif.com/creating-simple-tcpip-server-client-transfer-data-using-c-vb-net/, i just changed minor things to correct the file output)
I tried to use this with a friend of mine, but his router is uteer garbage, and it cant forward any ports whatsoever and wont even work with upnp. It is set to IpV6 as well, and as far as I know IPv6 doesnt need anymore port forwarding since every device has its own public ip.
sadly my program doesnt work with IPv6 adresses, and I have a hard time finding any information regarding this topic.
Here is my code:
Public Class Form1
Private nSockets As ArrayList
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim IPHost As IPHostEntry
IPHost = Dns.GetHostByName(Dns.GetHostName())
lblStatus.Text = "My IP address is " +
IPHost.AddressList(0).ToString()
nSockets = New ArrayList()
Dim thdListener As New Thread(New ThreadStart _
(AddressOf listenerThread))
thdListener.Start()
End Sub
Public Sub listenerThread()
Control.CheckForIllegalCrossThreadCalls = False
Dim tcpListener As New TcpListener(7080)
Dim handlerSocket As Socket
Dim thdstHandler As ThreadStart
Dim thdHandler As Thread
tcpListener.Start()
Do
handlerSocket = tcpListener.AcceptSocket()
If handlerSocket.Connected Then
lbConnections.Items.Add(
handlerSocket.RemoteEndPoint.ToString() +
"connected.")
SyncLock (Me)
nSockets.Add(handlerSocket)
End SyncLock
thdstHandler = New ThreadStart(AddressOf _
handlerThread)
thdHandler = New Thread(thdstHandler)
thdHandler.Start()
End If
Loop
End Sub
Public Sub handlerThread()
Dim handlerSocket As Socket
handlerSocket = nSockets(nSockets.Count - 1)
Dim networkStream As NetworkStream = New _
NetworkStream(handlerSocket)
Dim blockSize As Int16 = 16
Dim thisRead As Int16
Dim dataByte(blockSize) As Byte
SyncLock Me
' Only one process can access the
' same file at any given time
Dim fileStream As Stream
fileStream = File.OpenWrite("C:\Whatever.file")
While (True)
thisRead = networkStream.Read(dataByte,
0, dataByte.Length)
fileStream.Write(dataByte, 0, thisRead)
If thisRead = 0 Then Exit While
End While
fileStream.Close()
networkStream.Close()
End SyncLock
lbConnections.Items.Add("File Written")
handlerSocket = Nothing
End Sub
How do i make it IPv6 capable?
Forgot to put in my client, what do i have to change here to make it work? Since even with the changes to my server, its still not connecting properly.
Private Sub Sendfile()
Dim filebuffer As Byte()
Dim fileStream As Stream
fileStream = File.OpenRead(tbFilename.Text)
' Alocate memory space for the file
ReDim filebuffer(fileStream.Length)
fileStream.Read(filebuffer, 0, fileStream.Length)
' Open a TCP/IP Connection and send the data
Dim clientSocket As New TcpClient(tbServer.Text, 7080)
Dim networkStream As NetworkStream
networkStream = clientSocket.GetStream()
networkStream.Write(filebuffer, 0, fileStream.Length)
networkStream.Close()
End Sub
Your listener is currently listening to IPv4-address 0.0.0.0, which is the default when you only specify a port to the listener.
You need to use the TcpListener(IPAddress, Integer) overload and specify IPv6Any to listen to IPv6-addresses.
Dim tcpListener As New TcpListener(IPAddress.IPv6Any, 7080)
As a side note you should rather use a List(Of T) than an ArrayList. The latter is typeless and not as optimized for .NET as the former.

VB.NET TCPClient/Server Issue- Sending on a Timer

So my program starts out by counting how many processes of "XProcess" and has a timer to check every 1 second, which works great! I have the input of the count going into Setting variable. I then have a sub routine that takes that Setting variable, along with a IF statement to output that the TCPClient is sending the string ("One Process").
Well the issue is, I have no event to use with the sub routine and so I tied it in with the timer to send the message out every 1 second. The TCPClient sends it to a local address(127.0.0.1) right now, and sends it to a Textbox. Well PROBLEM!!!
It repeats ("One Process") over and over and over, which I can see why this happens.
So with the Code below, how can the TCPClient send an notification of how many processes of "XProcess" to the TCPServer and the TCPSERVER to spit out that 1 or more processes are running ? (with out the SERVER repeating the string (integer works as wel) over and over again)
The below works, but repeats how many processes are running as a string.
MainWindow.xaml.vb
Imports System.Windows.Threading
Imports System.Net.Sockets
Public Class MainWindow
Private Run_ProgramRunCheck_timer As New DispatcherTimer
Private Run_RecieveCheck_timer As New DispatcherTimer
Dim processCount As Integer
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
ServerStart()
'Check for program changes every second
' Set interval for timer
Run_ProgramRunCheck_timer.Interval = TimeSpan.FromMilliseconds(1000)
'Start timer on button click
Run_ProgramRunCheck_timer.Start()
AddHandler Run_ProgramRunCheck_timer.Tick, AddressOf __ProgramCheck
'Check for Message Recieve every second
' Set interval for timer
Run_RecieveCheck_timer.Interval = TimeSpan.FromMilliseconds(1000)
'Start timer on button click
Run_RecieveCheck_timer.Start()
AddHandler Run_RecieveCheck_timer.Tick, AddressOf _RecieveMessageConvert
TCPClientSender()
End Sub
Public Sub __ProgramCheck()
'This sub will be checked every 1 seconds for changes
'Count number of processes
processCount = Process.GetProcessesByName("tvnviewer").Count()
My.Settings.TotalProcesses = processCount
End Sub
Public Sub TCPClientSender()
My.Settings.TotalProcesses = 0
If My.Settings.TotalProcesses = 1 Then
Dim port As Int32 = 50000
Dim client As New TcpClient("127.0.0.1", port)
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes("One Process")
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
Dim stream As NetworkStream = client.GetStream()
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
End If
End Sub
Public Sub _RecieveMessageConvert()
TextBlock1.Text = My.Settings.StoreSentMessage
End Sub
End Class
TCPServer.vb
Imports System.Net
Imports System.Threading
Imports System.Net.Sockets
Imports System.IO
Public Module TCPServer
Dim Server = New TcpListener(IPAddress.Any, 50000) ' <-- Listen on Port 50,000
Dim Client As New TcpClient
Private ServerThread As Thread = Nothing
Dim Message As String = ""
Private Threads As New List(Of Thread)
Public Sub ServerStart()
ServerThread = New Thread(AddressOf ConnectionListener)
ServerThread.IsBackground = True
ServerThread.Start()
End Sub
Private Sub ConnectionListener()
Try
Server.Start()
While True
Dim client As TcpClient = Server.AcceptTcpClient ' Blocks until Connection Request is Received
Dim Reader As New StreamReader(client.GetStream())
While Reader.Peek > -1
Message = Message + Convert.ToChar(Reader.Read()).ToString
End While
My.Settings.StoreSentMessage = Message
End While
Catch ex As Exception
End Try
End Sub
End Module
Dont you just want to do this:
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(My.Settings.TotalProcesses)
I dont know how you ever get it to say "One Process" when you set the value to zero and then check if the value is 1 on the next line???
My.Settings.TotalProcesses = 0
If My.Settings.TotalProcesses = 1 Then

how to listen on port 25 with vb.net

I'm basically trying to write a spam filter for incoming email on a mail server. I'd like to write a VB.NET program that can listen for any incoming mail on port 25 and then run my script on it and then pass it to the mail server running on a different port.
What do I need to do to have my program just sit and wait for a message to come in on port 25 and then react to it?
Thanks.
Here, as an example, is part of a socket listening service I modified from a tutorial a while ago in VB.NET. Basically, a socket listens for traffic on port 25 when the service is started, accepts a connection and then assigns that connection to a new thread, sends a response, and then closes the TCP connection.
Dim serverSocket As New TcpListener(IPAddress.Any, "25")
Dim ipAddress As System.Net.IPAddress = System.Net.Dns.Resolve(System.Net.Dns.GetHostName()).AddressList(0)
Dim ipLocalEndPoint As New System.Net.IPEndPoint(IPAddress, 25)
Protected Overrides Sub OnStart(ByVal args() As String)
Dim listenThread As New Thread(New ThreadStart(AddressOf ListenForClients))
listenThread.Start()
End Sub
Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
End Sub
Private Sub ListenForClients()
serverSocket = New TcpListener(ipLocalEndPoint)
serverSocket.Start()
While True
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
While True
If (bytesRead = 0) Then
Exit While
End If
Dim encoder As New asciiencoding()
Dim serverResponse As String = "Response to send"
'Response to send back to the testing client
Dim sendBytes As [Byte]() = encoding.ascii.getbytes(serverResponse)
clientStream.Write(sendBytes, 0, sendBytes.Length)
End While
tcpClient.Close()
End Sub