Learn about TcpClient and TcpListener. To connect something need to be listening at the other end, a server, that is the job of the TcpListener. To start one create an instance where you specify which ip and port to listen from and call the Start method, keep it in a class variable. This is then needed at minimum at
server:
Private server As TcpListener
server = New TcpListener(ip, port)
server.Start()
The server ip is the local IP address you wish to bind to, here's an example retrieving it:
Dim localIP As Net.IPAddress = Net.Dns.GetHostAddresses("")(0)
With a Timer you can check Pending property to see if a client is attempting to connect, then AcceptTcpClient to establish the connection:
If server.Pending Then
client = server.AcceptTcpClient
The 'client' you can also keep in a class variable, it's functionality is same as described below for
communication.
Private client As TcpClient
At
client you can connect to the server with a TcpClient:
Private client As TcpClient
client = New TcpClient(ip, port)
For basic
communication sending strings it is most convenient using StreamWriter/StreamReader, these can read/write via the NetworkStream of the TcpClient, keep them in class variables:
Private reader As IO.StreamReader
Private writer As IO.StreamWriter
initialize them after connection is made:
reader = New IO.StreamReader(client.GetStream)
writer = New IO.StreamWriter(client.GetStream)
writer.AutoFlush = True
Now you can write messages with a call to WriteLine method:
writer.WriteLine("message")
and read with ReadLine method if data is available, use a Timer to check this at intervals:
If client.GetStream.DataAvailable Then
Dim msg As String = reader.ReadLine
The server and client functionality can be built into each client, so each client has the ability to receive connections. The server can also be a dedicated application that all clients connect to.
Finally I will mention
cleanups, the server listener is closed with a call to Stop method:
The sockets is closed by closing the NetworkStream of TcpClient
Since this example uses stream-reader/writer you can also close the socket by closing/disposing the reader/writer:
reader.Dispose()
writer.Dispose()
The TcpClient is released by calling Close method:
Hope this brief introduction to sockets help.
You will also need to use Try-Catch with several of these calls, as they may and will throw exceptions. Reading the documentation and trying out things will help you understand this.