Author Topic: VB.NET Simple Tcp Client Server App  (Read 7372 times)

0 Members and 1 Guest are viewing this topic.

Bill Tillman

  • Guest
VB.NET Simple Tcp Client Server App
« on: September 30, 2013, 05:30:11 PM »
I've been working on a project which has me stumped and I'm looking for any advice at all. I want to have a client app connect via TCP to a server and transmit a stream. The stream gets processed by the server and the resulting information is feed back to the client, whereupon the client will close it's connection with the server and the server will close it's connection with the client and the server will then wait for the next client request.

Here is the server side I have so far. It will let me connect with a client and I think that end is almost complete...maybe. But mostly with this multi-threaded server I need a way to make it shutdown using Button2 without shutting down the entire app. In other words, shut down the TcpListener, then be able to restart it again with Button1.

Code: [Select]
Imports System.Net.Sockets
Imports System.Text
Imports System.Net

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Control.CheckForIllegalCrossThreadCalls = False
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        multi_server()
    End Sub

    Private Sub multi_server()
        Dim thread As System.Threading.Thread
        thread = New System.Threading.Thread(AddressOf Hosting_Port)
        thread.Start()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
          THIS IS WHERE IT WANT TO MAKE THE TcpListener Stop
    End Sub

    Private Sub Hosting_Port()
        Const portNumber As Integer = 65535
        Dim TcpListener As New TcpListener(IPAddress.Parse("127.0.0.1"), portNumber)
        TcpListener.Start()
        ListBox1.Items.Add("[SERVER] Waiting for connection...")
        Try
            'Accept the pending client communication and return
            'a TcpClient initialized for communication
            Dim tcpClient As TcpClient = TcpListener.AcceptTcpClient()
            ListBox1.Items.Add("[SERVER] Commection Accepted.")

            '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)
            ListBox1.Items.Add(("[SERVER] Client sent: " + clientdata))
            Dim responseString As String = "Connected to server."
            Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
            networkStream.Write(sendBytes, 0, sendBytes.Length)
            ListBox1.Items.Add(("[SERVER] Message Sent /> : " + responseString))

            'Any communication with the remote client using the TcpClient can go here.
            'Close TcpListener and TcpClient
            tcpClient.Close()
            ListBox1.Items.Add("[SERVER] exit")

        Catch ex As Exception
            ListBox1.Items.Add(ex.Message)

        End Try
    End Sub

End Class

« Last Edit: September 30, 2013, 05:33:46 PM by Bill Tillman »

Bill Tillman

  • Guest
Re: VB.NET Simple Tcp Client Server App
« Reply #1 on: September 30, 2013, 05:49:43 PM »
Okay, you guys have to understand just how damn good you really are. Five seconds after I posted this, I may seem to have found my problem. Just telepathically (or maybe pathetically) I received what may be the solution. Okay, so I moved the declarations for TcpListener and portNumber to be outside of the sub Hosting_Port, just below the Public Class Form1 line. And it at least appears to now let me start and stop the TcpListener. Or maybe not. In the ListBox1 I see a line which states, "A blocking operation was interrupted by a call to WSACancelBlockingCall". Does this mean I f'ed up or does it mean the TcpListener was closed down. And I guess I should come up with a way to close down any and all TcpClient connections as this is being done. But this app is so simple and so predictable that it will almost never have open client connections because they will open and close in a matter of seconds. The client will send in its stream, get an answer back and then close it connection.

There is also this point. The guy who tipped me off to this code told me that I would need to include this in the Form1 Load sub:
Code: [Select]
Control.CheckForIllegalCrossThreadCalls = False

I was warned that this could be dangerous, but again this app will be running on a LAN that is deep inside about 3 different firewall routers and the IT guys assure me they know what they are doing. Plus this app is so specialized that even if someone were to send in a stream, the main app that runs on this will just dump it into the bit bucket if it don't make sense to it.
« Last Edit: September 30, 2013, 05:53:31 PM by Bill Tillman »