I' trying hard to create TCP server and client. I got a lot of tutorials like here and here. But still can't succeed!
Here is my code:
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Runtime.InteropServices
Public Class Form1
Private Server As TcpListener = Nothing
Private ServerThread As Thread = Nothing
Private WithEvents Tray As New NotifyIcon
Private myClient As TcpClient = Nothing
Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.115")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Shown
Server = New TcpListener(localAddr, 40000)
ServerThread = New Thread(AddressOf ConnectionListener)
ServerThread.IsBackground = True
ServerThread.Start()
TextBox1.Text = "Server is ready!"
' function I use to get all the TCP clients I can see in local web.
' You can find it by the first link (see at the top of the post)
lbComputers.DataSource = GetNetworkComputers()
End Sub
Private Sub ConnectionListener()
Try
Server.Start()
While True
myClient = Server.AcceptTcpClient
'myClient.Connect("MSK4", 40000) 'tried this: didn't work
Dim T As New Thread(AddressOf SomeClientActions)
T.Start(myClient)
TextBox2.Text = "Client connected" ' It's always empty :(
End While
myClient.Close()
End While
Catch ex As Exception
MessageBox.Show("Unable to Accept Connections", "Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
Application.ExitThread()
End Sub
Private Sub SomeClientActions(ByVal client As Object)
' ... do something with "client" in here ...
Invoke(Sub() TextBox2.Text = "This text is never appears :(")
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
'myClient.Close() 'error is here
Server.Stop()
End Sub
End Class
And I have two TextBoxes (TextBox1 and TextBox2). I get Server is ready!
in the first one but never get anything in the second! So I suppose I can't connect to my server! Code after this row:
myClient = Server.AcceptTcpClient
Is never executes. I tried to use just
myClient.Connect("MSK4", 40000)
As my computer name is MSK4 but then I get my exception and MessageBox. How to realize the connect? What I do wrong?
Making the server listen to 127.0.0.115
means it will only accept connections from that specific IP. To listen for connections from any IP you need to specify 0.0.0.0
or IPAddress.Any
.
As for making connections you must use IP-addresses only, computer names won't work.