Help with server side

robo100

Member
Joined
Dec 13, 2005
Messages
14
Location
New Mexico
Programming Experience
3-5
I have an application that I would like to send TCP data to another machine running the same application. The data is contained in a simple and short string so I thought the easiest way is to use the system.net.socket and the tcpclient and tcpserver to send and receive the data. When I start the application on one machine and activate the server portion of the code it just sits there waiting for data from the client. The problem is that I want it to be able to receive the data but have it transparent to the end user so they can use other functions in the application, but the problem is as long as the tcpserver is open the application is locked until it receives data from the client. How do I make sure the application doesnt lockup but will still recieve data from the client?

On the client side everything works great and I can send the text string to the application running the server code. Once the server gets the data it closes the tcp connection and runs like normal. I know the line that makes the server lockup is when I define the tcpclient:
VB.NET:
Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()

Once this line is executed the code just sits there waiting for the client. How do I get around this? Is this a place where using the threading is useful? As you can tell I am very new to programming and I am just not real sure how to do this.

Here is the full code for the server:

VB.NET:
Const portNumber As Integer = 8000
Dim tcpListener As New TcpListener(portNumber)
tcpListener.Start()
 
Try
Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
 
' Get the stream
Dim networkStream As NetworkStream = tcpClient.GetStream()
 
' Read the stream into a byte array
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
 
' Return the data received from the client to the console.
Dim clientdata As String = Encoding.ASCII.GetString(bytes)
MsgBox("Recieved data: " + clientdata)
 
Dim responseString As String = "Connected to server."
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
networkStream.Write(sendBytes, 0, sendBytes.Length)
tcpClient.Close()
tcpListener.Stop()
Catch
MsgBox("Unable to read")
End Try
 
Last edited by a moderator:
Back
Top