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
Related
I have a thread and a socket server for listening to client. Client software is not for me and it is a Laboratory Software that sends data to my program.
when listening starts there is no problem but when the client software is closed and reopened, that can not send any data to my software.
My listener must be run every time like a service.
This is my code:
Delegate Sub WriteMsgHandle(ByVal Msg As String)
Dim handler As WriteMsgHandle
Dim THS As ThreadStart
Dim TH As Thread
Private Sub btnListen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListen.Click
Try
btnListen.Enabled = False
THS = New ThreadStart(AddressOf Listen)
TH = New Thread(THS)
TH.Start()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Public Sub Listen()
Dim bytesReceived As Integer = 0
Dim recv() As Byte = New Byte(1) {}
Dim clientSocket As Socket
Dim listenerSocket As New Socket _
(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim IPHost As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
Dim localadd As IPAddress = IPAddress.Parse(txt_ip.Text)
Dim ipepServer As IPEndPoint = New IPEndPoint(localadd, txt_port.Text)
handler = AddressOf WriteMsg
listenerSocket.Bind(ipepServer)
listenerSocket.Listen(-1)
clientSocket = listenerSocket.Accept()
Dim msgcount As Integer = 0
If clientSocket.Connected Then
MsgBox("Connected")
Do
bytesReceived = clientSocket.Receive(recv)
Dim Msg As String
Msg = Encoding.ASCII.GetString(recv)
Invoke(handler, Msg)
Loop While bytesReceived <> 0
End If
End Sub
You're only accepting once. You need to accept in a loop.
If clientSocket.Connected Then why did you add this? Delete that check. The socket was just accepted so it is connected. Even if it was disconnected do you want to just ignore that error condition?!
The receive loop is correct.
You probably want to start each accepted client on a new thread (or use async IO).
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
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
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.
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.