How to send and receive text over TCP with VB.Net 2005

JTBob

Member
Joined
Feb 24, 2006
Messages
8
Programming Experience
10+
Hi,

I'm just starting to use VB.Net 2005 after using VB6 for so many years. Fun learning curve. And unfortunately my reference books still haven't arrived yet. I found some class libraries on the net, but they were all written for VB.Net 2003, which required more editting to make work in 2005 than I knew how to do.

So, I'm hoping someone here can help. I'm looking for something really simple. I need to send a small text string to another computer and then get the response text string from that system.

I've seen some of the code offered for sending files, but I'm guessing that won't all work for my requirements.

Thanks for any assistance,
Robert
 
The TcpClient and TcpListener classes in the System.Net.Sockets namespace is what you seek.
Here is an article with small code examples for both client/server: http://www.eggheadcafe.com/articles/20020323.asp
There are code examples for both in the .Net Framework documentation too.
 
Hi John,

I finally got down to trying out some of the code from the link you gave to put together a simple client. Here's what I pieced together.

Dim tcpClient As New System.Net.Sockets.TcpClient()
Try
tcpClient.Connect("xxx.xxx.xxx.xxx", 1550)
Dim networkStream As NetworkStream = tcpClient.GetStream()
If networkStream.CanWrite And networkStream.CanRead Then
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("$gimme")
networkStream.Write(sendBytes, 0, sendBytes.Length)
' Read the NetworkStream into a byte buffer.
Do
Loop Until networkStream.DataAvailable
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
Dim returndata As String = Encoding.ASCII.GetString(bytes)
Label1.Text = returndata
tcpClient.Close()
Else
If Not networkStream.CanRead Then
tcpClient.Close()
Else
If Not networkStream.CanWrite Then
tcpClient.Close()
End If
End If
End If
Catch ex As Exception
Label1.Text = "Exception Caught"
End Try

I put this code inside a button click. Ran it and all I get in the label is:
"Connection made to Socket Server!"

There should be more data after that, but I don't see anything. I used HyperTerminal to connect to the same address and port and I got the same thing, but I also got the data requested when I typed: $gimme

Any ideas on why I'm not getting anything other than the made connection string?

Thanks,
Robert
 
Label1.Text = returndata
tcpClient.Close()

... if I understood the question
 
Hi John,

I thought what I was trying was fairly simple, but this socket stuff is getting rather more involved than I thought. I wish my reference manuals would arrive.

Basically, I'm looking for something simple (or at least I thought it was). Open a connection to a polled data server, send a short message to request data, which is "$gimme" right now. Then read what comes in response.

The code that I listed before would connect, then receive the message "Connection made to Socket Server!". But it's the stuff after that that I want. It seems this statement is passed to my code when the connection is made to the server.

I tried moving the code around into a subroutine and using Select Case to arrange the code in Connecting, Sending, Receiving, and Closing the socket. But now I get an error message that says "Reference to a non-shared member requires an object reference".

So now I'm back to my original code snippet that connects the socket, writes out the "$gimme" text, gets the response, then closes. Is there a better method for all this? What I'd really like to do is open the connection when the program starts, then write the request statement and receive the return data when some user event occurs, then shut down the connection when the program closes.

Thanks for your help,
Robert
 
Hi John,

I finally got my code to function, which I've placed into a function call to retrieve requested data. After the connection to the tcpClient was made, I did my call to get requested data. I though I could get the requested data in my read buffer, but I kept getting "Connection made to Socket Server!", which I think was being sent by the server after the connection was made. Whether a write is done after the connection or not, that same message sits in the read buffer. Even if I change the write message in the first write, I still see the connected response.

But if I send a second write to the networkstream, I then get the data I really want in my read buffer. Here is the code I used:

Function GetSCSMessage(ByVal IP As String, ByVal Port As Int32) As String
Dim tcpClient As New System.Net.Sockets.TcpClient()
Try
tcpClient.Connect(IP, Port)
tcpClient.NoDelay = True
Dim networkStream As NetworkStream = tcpClient.GetStream()
If networkStream.CanWrite And networkStream.CanRead Then
' Do a simple write.
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("$gimme")
networkStream.Write(sendBytes, 0, sendBytes.Length)
' Read the NetworkStream into a byte buffer.
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
' Output the data received from the host to the console.
Dim ReturnData As String = Encoding.ASCII.GetString(bytes)
If InStr(ReturnData, "Socket Server") > 0 Then
' Rewrite output to server to get real data
networkStream.Write(sendBytes, 0, sendBytes.Length)
Dim newbytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(newbytes, 0, CInt(tcpClient.ReceiveBufferSize))
ReturnData = Encoding.ASCII.GetString(newbytes)
End If
Dim i As Integer = InStr(ReturnData, Chr(0), CompareMethod.Binary)
ReturnData = Microsoft.VisualBasic.Left(ReturnData, i - 1)
GetSCSMessage = ReturnData
tcpClient.Close()
Else
If Not networkStream.CanRead Then
tcpClient.Close()
Else
If Not networkStream.CanWrite Then
tcpClient.Close()
End If
End If
GetSCSMessage = ""
End If
Catch ex As Exception
GetSCSMessage = ""
MsgBox("Could not connect to SCS: " & ex.ToString, MsgBoxStyle.Critical, "Connection Error")
End Try
End Function


In the IF/EndIf block with the test for InStr>0, is the second write to the data server. Basically my code is working, but I'm a little confused as to why it takes a second write to the networkstream to get the data I want.

Please let me know if you have any insights.

Thanks again for all your help.

Cheers,
Robert
 
Is the server also under your control, or just the client? You've been posting client code, but nothing server-side...

If you don't have any control over how the server you're connecting to operates, it's entirely possible that the second-command-required is how the server was designed to operate...

If you *do* have control of server code (the tcpListener side of the equation), could you post it so we can see if maybe something on that end is goofy?
 
Hi,

Thanks for the reply. Sorry, the server isn't under my control, other than to get the software to listen to a port for requests.

It was just interesting that was what I had to go through to get the data I needed. The manual I have for the program doesn't state anything about that. But if that's the way it works, then that's what I'll conform to in my program.

Cheers,
Robert
 
Back
Top