Hi Folks!
I’m trying to make a client/server program using VB.NET. I’ve got an example from MSDN website. After some changes, I got a working version. Everything is working fine, however there is a weird delay when client sends a package to server. I’m running it in my LAN and it shouldn’t take 20 seconds to send an 18-character-long string. Code below:
Thanks for your help!
**SERVER side**
Try
Dim server As System.Net.Sockets.TcpListener
server = Nothing
Dim localAddr As System.Net.IPAddress = System.Net.IPAddress.Parse("192.168.1.2")
Dim port As Int32 = 13000
server = New System.Net.Sockets.TcpListener(localAddr, port)
' Start listening for client requests.
server.Start()
' Buffer for reading data
Dim bytes(256) As Byte
Dim data As String = Nothing
' Enter the listening loop.
While True
lblMessage.Text = "Waiting for connection..."
' Perform a blocking call to accept requests.
Dim client As System.Net.Sockets.TcpClient = server.AcceptTcpClient()
lblMessage.Text = "Connected"
data = Nothing
' Get a stream object for reading and writing
Dim stream As System.Net.Sockets.NetworkStream = client.GetStream()
Dim i As Int32
i = stream.Read(bytes, 0, bytes.Length)
' Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
' analyse data sent...
lblMensagem.Text = "Data OK. Doing the job..."
' Send back a response.
Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes("OK")
stream.Write(msg, 0, msg.Length)
' Shutdown and end connection
client.Close()
End While
Catch ex As System.Net.Sockets.SocketException
MessageBox.Show(ex.ToString())
End Try
**CLIENT side**
Try
Dim client As New System.Net.sockets.TcpClient("192.168.1.2", 13000)
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes("8888;888.88;888.88")
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
Dim stream As System.Net.sockets.NetworkStream = client.GetStream()
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
' Receive the TcpServer.response.
' Buffer to store the response bytes.
data = New [Byte](256) {}
' String to store the response ASCII representation.
Dim responseData As [String] = [String].Empty
' Read the first batch of the TcpServer response bytes.
Dim bytes As Int32 = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
' Close everything.
stream.Close()
client.Close()
Catch ex As System.Net.Sockets.SocketException
MessageBox.Show(ex.ToString())
End Try