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.
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