I've created a Windows service that waits for TCPClient connections and relays any messages to all connected clients (except the sender). My code is based on this example.
One client connects when an event is triggered, sends some progress updates and then disconnects. The other clients are front end applications that receive and display the update.
If these clients are left idle for several hours they seem to loose the connection without any error\warning. I cannot find any relevent timouts for idle periods, is there something I am missing?
Service Code:
Protected Overrides Sub OnStart(ByVal args() As String)
_Listener = New TcpListener(IPAddress.Any, 1314)
_Listener.Start()
ListenForClient()
_ConnectionMontior = Task.Factory.StartNew(AddressOf DoMonitorConnections, New MonitorInfo(_Listener, _Connections), TaskCreationOptions.LongRunning)
End Sub
Private Sub ListenForClient()
Dim info As New ConnectionInfo(_Listener)
_Listener.BeginAcceptTcpClient(AddressOf DoAcceptClient, info)
End Sub
Private Sub DoAcceptClient(result As IAsyncResult)
Try
Dim monitorInfo As MonitorInfo = CType(_ConnectionMontior.AsyncState, MonitorInfo)
If monitorInfo.Listener IsNot Nothing AndAlso Not monitorInfo.Cancel Then
Dim info As ConnectionInfo = CType(result.AsyncState, ConnectionInfo)
monitorInfo.Connections.Add(info)
info.AcceptClient(result)
ListenForClient()
info.AwaitData()
End If
Catch ex As Exception
WriteToEventLog("DoAcceptClient: " & ex.Message)
End Try
End Sub
Private Sub DoMonitorConnections()
Try
'Create delegate for updating output display
' Dim doAppendOutput As New Action(Of String)(AddressOf AppendOutput)
'Get MonitorInfo instance from thread-save Task instance
Dim monitorInfo As MonitorInfo = CType(_ConnectionMontior.AsyncState, MonitorInfo)
'Implement client connection processing loop
Do
'Create temporary list for recording closed connections
Dim lostConnections As New List(Of ConnectionInfo)
'Examine each connection for processing
For Each info As ConnectionInfo In monitorInfo.Connections
If info.Client.Connected Then
'Process connected client
If info.DataQueue.Count > 0 Then
'The code in this If-Block should be modified to build 'message' objects
'according to the protocol you defined for your data transmissions.
'This example simply sends all pending message bytes to the output textbox.
'Without a protocol we cannot know what constitutes a complete message, so
'with multiple active clients we could see part of client1's first message,
'then part of a message from client2, followed by the rest of client1's
'first message (assuming client1 sent more than 64 bytes).
Dim messageBytes As New List(Of Byte)
While info.DataQueue.Count > 0
messageBytes.Add(info.DataQueue.Dequeue)
End While
'Relay the message to all clients except the sender
For Each inf As ConnectionInfo In monitorInfo.Connections
If inf.Client.Connected Then
Dim msg As String = info.Client.Client.RemoteEndPoint.ToString & "|" & System.Text.Encoding.ASCII.GetString(messageBytes.ToArray)
If Not inf.Client.Client.RemoteEndPoint.ToString = msg.Split("|")(0) Then
inf.Client.Client.Send(messageBytes.ToArray)
End If
End If
Next
End If
Else
'Record clients no longer connected
lostConnections.Add(info)
End If
Next
'Clean-up any closed client connections
If lostConnections.Count > 0 Then
While lostConnections.Count > 0
monitorInfo.Connections.Remove(lostConnections(0))
lostConnections.RemoveAt(0)
End While
End If
'Throttle loop to avoid wasting CPU time
_ConnectionMontior.Wait(1)
Loop While Not monitorInfo.Cancel
'Close all connections before exiting monitor
For Each info As ConnectionInfo In monitorInfo.Connections
info.Client.Close()
Next
monitorInfo.Connections.Clear()
Catch ex As Exception
WriteToEventLog("DoMonitorConnections" & ex.Message)
End Try
End Sub
Client Code:
_ServerAddress = IPAddress.Parse(ServerIP)
_Connection = New ConnectionInfo(_ServerAddress, 1314, AddressOf InvokeAppendOutput)
_Connection.AwaitData()
ConnectionInfo Class:
Public Class ConnectionInfo
Private _AppendMethod As Action(Of String)
Public ReadOnly Property AppendMethod As Action(Of String)
Get
Return _AppendMethod
End Get
End Property
Private _Client As TcpClient
Public ReadOnly Property Client As TcpClient
Get
Return _Client
End Get
End Property
Private _Stream As NetworkStream
Public ReadOnly Property Stream As NetworkStream
Get
Return _Stream
End Get
End Property
Private _LastReadLength As Integer
Public ReadOnly Property LastReadLength As Integer
Get
Return _LastReadLength
End Get
End Property
Private _Buffer(255) As Byte
Public Sub New(address As IPAddress, port As Integer, append As Action(Of String))
_AppendMethod = append
_Client = New TcpClient
_Client.Connect(address, port)
_Stream = _Client.GetStream
End Sub
Public Sub AwaitData()
_Stream.BeginRead(_Buffer, 0, _Buffer.Length, AddressOf DoReadData, Me)
End Sub
Public Sub Close()
If _Client IsNot Nothing Then _Client.Close()
_Client = Nothing
_Stream = Nothing
End Sub
Private Const MESSAGE_DELIMITER As Char = ControlChars.Cr
Dim sBuilder As New System.Text.StringBuilder
Private Sub DoReadData(result As IAsyncResult)
Dim info As ConnectionInfo = CType(result.AsyncState, ConnectionInfo)
Try
If info._Stream IsNot Nothing AndAlso info._Stream.CanRead Then
info._LastReadLength = info._Stream.EndRead(result)
If info._LastReadLength > 0 Then
Dim message As String = System.Text.Encoding.UTF8.GetString(info._Buffer, 0, info._LastReadLength)
If (message.IndexOf(MESSAGE_DELIMITER) > -1) Then
Dim subMessages() As String = message.Split(MESSAGE_DELIMITER)
sBuilder.Append(subMessages(0))
If Not info._Client.Client.LocalEndPoint.ToString = sBuilder.ToString.Split("|")(0) Then
info._AppendMethod(sBuilder.ToString)
End If
sBuilder = New System.Text.StringBuilder
If subMessages.Length = 2 Then
sBuilder.Append(subMessages(1))
Else
For i As Integer = 1 To subMessages.GetUpperBound(0) - 1
'MessageBox.Show(subMessages(i))
info._AppendMethod(subMessages(i))
Next
sBuilder.Append(subMessages(subMessages.GetUpperBound(0)))
End If
Else
sBuilder.Append(message)
End If
End If
End If
info.AwaitData()
Catch ex As Exception
info._LastReadLength = -1
End Try
End Sub
End Class
TCP does not guarantee that a side not trying to send data can detect a loss of the connection. You should have taken this into account when you designed your application protocol.
What you are seeing is most commonly caused by NAT or stateful firewalls. As a practical matter, if you don't send data at least every ten minutes, you can expect at least some clients to get disconnected. Their NAT devices or stateful firewalls simply forget about the connection. Neither side notices until it tries to send data.
I would suggest creating some kind of dummy message that the server sends to all its clients every five minutes. Basically, this is just some small chunk of data that can be uniquely identified as serving only to keep the connection alive.
Each client responds to the dummy message by sending a dummy message back to the server. If a client doesn't receive a dummy message in ten minutes, it should consider the connection lost, close it, and try to connect again.
The mere act of trying to send the dummy message will cause the server to detect any lost connections, but you should probably also consider as dead any connection to a client that hasn't responded to a dummy message by the time you're ready to send the next one. The client will know a connection is lost when it doesn't receive the dummy message. The exchange of messages will keep the NAT/firewall entry alive.
Related
I have a working TCP / IP server that can listen to one or many clients, it is working great! It can received and send data from one client.
My problem is whenever I clicked the listen button then un-listen by clicking again the button my application freeze. The only way to free my application from this freeze is to connect another client while my system is still in the process of un-listening.
The second problem involves receiving data from multiple clients, yes it can listen and allow multiple clients to be connected to the server but it doesn't received all the messages sent by the client, it only receives the message of the first client.
Here's what my system look like.
And here's my code
Imports System.Net.Sockets
Imports System.Net
Imports System.Threading 'Imports Threading Namespace
Imports System.Text
Imports System.Reflection
Public Class Form1
Dim stream As NetworkStream
Dim client As TcpClient
Dim port As Int32
Dim localAddr As IPAddress = IPAddress.Any
Dim server As TcpListener
Dim tcpClientThread As System.Threading.Thread
Dim PublicIP = String.Empty 'The IP and Port of the Client that connects to port 7700
Private Sub Tcpclient()
port = NUD_Tcp_Port.Value
' The statement of TCPClient function
server = Nothing
' Buffer for reading data
Dim bytes(1024) As Byte
Try
server = New TcpListener(localAddr, port) 'Set the TcpListener on port 13000.
server.Start() 'Start listening for client requests.
writeData(Server_IP_Port) 'Outputs the server's ip and port listening
'Perform a blocking call to accept requests.
'You could also user server.AcceptSocket() here.
client = server.AcceptTcpClient()
writeData("Connected: " & Client_IP_Port())
Dim data As String = Nothing 'The data we received from client, set the default value to nothing
stream = client.GetStream() 'Get a stream object for reading and writing
Dim i As Int32 = stream.Read(bytes, 0, bytes.Length) 'Loop to receive all the data sent by the client.
While (i <> 0)
'Translate data bytes to a ASCII string.
data = Encoding.ASCII.GetString(bytes, 0, i)
writeData("Received: " & data)
'Process the data sent by the client.
data = data.ToUpper()
Dim msg As Byte() = Encoding.ASCII.GetBytes(data)
i = stream.Read(bytes, 0, bytes.Length)
End While
Catch haha As SocketException
Console.WriteLine("SocketException: {0}", haha)
Finally
'server.Stop()
End Try
End Sub
Function Client_IP_Port() As String 'Gets the IP and port number of clients who connected to our server
If PublicIP = String.Empty Then
Try
' Get the clients IP address using Client property
Dim ipend As Net.IPEndPoint = client.Client.RemoteEndPoint
If Not ipend Is Nothing Then
PublicIP = ipend.Address.ToString & " : " & ipend.Port.ToString
End If
Catch ex As System.ObjectDisposedException
PublicIP = String.Empty
Catch ex As SocketException
PublicIP = String.Empty
End Try
End If
Return PublicIP
End Function
Function Server_IP_Port() 'Get the IP and port number of server that it listens
Dim IPListening = IPAddress.Parse(CType(server.LocalEndpoint, IPEndPoint).Address.ToString()).ToString
Dim PortListening = CType(server.LocalEndpoint, IPEndPoint).Port.ToString()
If IPListening = "0.0.0.0" Then
IPListening = "any IP Address"
End If
Return "Listening on " & IPListening & " : " & PortListening
End Function
Private Sub Tcp_Send(Msg_Send As String)
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(Msg_Send)
stream.Write(sendBytes, 0, sendBytes.Length)
writeData("Sent: " & Msg_Send)
End Sub
Public Sub StopListen() 'Function to telll to the server to stop listening
Try
client.Close()
Catch err As Exception
Console.WriteLine(err)
End Try
tcpClientThread.Abort()
server.Stop()
Btn_Listen.Text = "Listen"
End Sub
Private Sub Btn_Listen_Click(sender As Object, e As EventArgs) Handles Btn_Listen.Click
If Btn_Listen.Text = "Listen" Then
tcpClientThread = New System.Threading.Thread(AddressOf Me.Tcpclient)
tcpClientThread.Start()
Btn_Listen.Text = "Close"
Else
StopListen()
End If
End Sub
Private Sub writeData(ByVal data As Object)
If InvokeRequired Then
Invoke(New Action(Of Object)(AddressOf writeData), data)
Else
RichTextBox1.AppendText(Environment.NewLine & data)
End If
End Sub
Private Sub Btn_Send_Click(sender As Object, e As EventArgs) Handles Btn_Send.Click
Tcp_Send(TB_Tcp_Send.Text)
End Sub
End Class
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.
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
I'm trying to test a scenario where one server accepts multiple connections or multiples clients.
The purpose is forwarded the data to another server with a different IP and different port. At the time of forwarding the data whenever I view different connections on the other server.
This is my code:
Private Sub ConectarTcp(ByVal id_gps As String, ByVal data As String)
Try
With WinSockClient
.IPDelHost = "192.168.5.8"
.PuertoDelHost = 3030
.Conectar()
End With
WinSockCliente.EnviarDatos(trama)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub Conectar()
Dim tcpClnt As TcpClient
Dim tcpThd As Thread
tcpClnt = New TcpClient()
tcpClnt.Connect(IPDelHost, PuertoDelHost)
Stm = tcpClnt.GetStream()
tcpThd = New Thread(AddressOf LeerSocket)
tcpThd.Start()
End Sub
Public Sub EnviarDatos(ByVal Datos As String)
Dim BufferDeEscritura() As Byte
BufferDeEscritura = Encoding.ASCII.GetBytes(Datos)
If Not (Stm Is Nothing) Then
'Envio los datos al Servidor
Stm.Write(BufferDeEscritura, 0, BufferDeEscritura.Length)
End If
End Sub
I have two applications running on different computers, one of them is a client and the other one is a server, the communication on Client -> Server works perfectly, although it doesn't on the opposite direction.
Server code:
Imports System.IO
Imports System.Net
Public Class Form1
Dim listener as Net.Sockets.TcpListener
Dim listenThread as Threading.Thread
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
listener = New Net.Sockets.TcpListener(Net.IPAddress.Any, 32111)
listener.Start()
listenThread = New Threading.Thread(AddressOf DoListen)
listenThread.IsBackground = True
listenThread.Start()
End Sub
Private Sub DoListen()
Dim sr As IO.StreamReader
Dim sw As IO.StreamWriter
Do
Try
Dim client As Net.Sockets.TcpClient = listener.AcceptTcpClient
sr = New IO.StreamReader(client.GetStream)
sw = New IO.StreamWriter(client.GetStream)
Dim Lines As String() = sr.ReadToEnd.Split(New Char() {","c}) 'get client data
sr.Close()
sw.Write("Message123") ' try to send data to client
sw.Close()
Catch
End Try
Loop
End Sub
End Class
Client code:
Public Class Form1
Dim Command As String
Dim thread As Threading.Thread
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
thread = New Threading.Thread(AddressOf MyProcess)
thread.IsBackground = True
thread.Start()
End Sub
Private Sub Send(ByVal Command As String)
Try
Dim client As New System.Net.Sockets.TcpClient
client.Connect(TextBox1.Text, 32111)
Dim writer As New IO.StreamWriter(client.GetStream)
writer.Write(Command)
writer.Flush()
client.Close()
MsgBox("Command has been sent successfully")
Catch ex As Exception
End Try
End Sub
Private Sub MyProcess()
Do
Dim client As New System.Net.Sockets.TcpClient
client.Connect("192.168.1.2", 32111)
Dim reader As New IO.StreamReader(client.GetStream)
MessageBox.Show(reader.ReadToEnd)
reader.Close()
client.Close()
Loop
End Sub
End Class
The thing is that nothing happens, the MessageBox doesn't appear on the client saying "Message123".
Each time the client creates a new socket and connects to it, it opens an entirely new channel of communication between the two applications. In your example, the server is returning a message on the first socket, but on the client it does not try to read from the first socket. instead, it opens a second socket and reads from that. You need to change it so that you are reading from the same socket on which you sent the request message.
If you think about it, you are making an assumption which can't possibly be true. You are assuming that there can only be one valid socket from your client machine to the server on that port. However obviously this is not true. You can run many separate FTP clients and to the same server, for instance. Each application can open as many sockets to the same port on the same server as they want to, and they are all completely independent from each other.