TCP Client program won't connect to my server - vb.net

I'm trying to create a basic chat server-client program using TCP/IP and port forwarding in VB.NET. The code is derived almost entirely from Carlo De Silva's YouTube tutorials. I'm consistently having an issue connecting the two clients. When I open the client on my computer and another client on the other computer, I get the error "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond [ip]:5757"
There are three different programs: the server, the client, and the client on the other end (the friend client.) The server and the client both use my local IP, which is accessed programmatically, so it couldn't be due to a typo. The friend client uses my external IP, which I've checked as of today (2018-09-09) and it is correct. I've set up port-forwarding on my router using TCP&UDP with my local IP, which was different when I checked it today, but I've updated the rule and the problem persists. Everything is done over port 5757. The firewall isn't an issue - I tried turning it off on the other computer and the friend client still fails to connect.
I've checked the port-forwarding tester on the website yougetsignal.com, which says that port 5757 is closed on both my local and external IP. But at the time of writing, I've currently got open the server and two client programs (both of which use my local IP,) and I am able to successfully send messages between those two client programs. So if they are able to send messages between the server and back, I don't understand why the website says that the port is closed on my local IP.
Can anyone help me work out why the friend client is failing to connect?
Server code:
Module MainModule
Dim _server As TcpListener
Dim _listOfClients As New List(Of TcpClient)
Dim hostName As String = System.Net.Dns.GetHostName
Dim ip As String = System.Net.Dns.GetHostEntry(hostName).AddressList(0).ToString
Dim extip As String = "86.25.175.94"
Dim port As Integer = 5757
Sub Main()
Console.Title = "SERVER"
Try
_server = New TcpListener(IPAddress.Parse(ip), port)
_server.Start()
Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
End Sub
Private Sub NewClient(state As Object)
Dim client As TcpClient = _server.AcceptTcpClient
Try
Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient)
_listOfClients.Add(client)
Dim ns As NetworkStream = client.GetStream
While True
'Creates a buffer
Dim toReceive(100000) As Byte
Dim length As Integer = ns.Read(toReceive, 0, toReceive.Length)
Dim text As String = Encoding.ASCII.GetString(toReceive, 0, length)
For Each c As TcpClient In _listOfClients
If c IsNot client Then 'Sends a message to every other client besides this one.
Dim nns As NetworkStream = c.GetStream 'New Network Stream
nns.Write(Encoding.ASCII.GetBytes(text), 0, text.Length)
End If
Next
Console.WriteLine(text)
Console.WriteLine()
'Sends a received message receipt.
Dim toSend() As Byte = Encoding.ASCII.GetBytes("Message Received...")
ns.Write(toSend, 0, toSend.Length)
End While
Catch ex As Exception
If _listOfClients.Contains(client) Then
_listOfClients.Remove(client)
End If
Console.WriteLine(ex.Message)
End Try
End Sub
End Module
Client code:
Module MainModule
Dim _client As TcpClient
Dim hostName As String = System.Net.Dns.GetHostName
Dim ip As String = System.Net.Dns.GetHostEntry(hostName).AddressList(0).ToString
Dim extip As String = "86.25.175.94"
Dim port As Integer = 5757
Sub Main()
Console.Title = "Chat Client (Host)"
Try
'Gets the local ip address
_client = New TcpClient(ip, port)
'This thread listens for receiving messages from the server.
Threading.ThreadPool.QueueUserWorkItem(AddressOf ReceiveMessages)
While True
'Starts a new stream
Dim ns As NetworkStream = _client.GetStream()
Dim message As String = Console.ReadLine()
Dim toSend() As Byte = Encoding.ASCII.GetBytes(message)
'Sends the message to the server
ns.Write(toSend, 0, toSend.Length)
End While
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
End Sub
Private Sub ReceiveMessages(state As Object)
Try
While True
'Starts a new network stream (receiving stream) to listen for any receiving messages.
Dim rs As NetworkStream = _client.GetStream
'Creates a buffer to receive text
Dim toReceive(100000) As Byte
'Reads anything coming in from the server.
Dim length As Integer = rs.Read(toReceive, 0, toReceive.Length)
'Converts the byte to text
Dim text As String = Encoding.ASCII.GetString(toReceive, 0, length)
Console.ForegroundColor = ConsoleColor.Green
Console.WriteLine(text)
Console.ResetColor()
Console.WriteLine()
End While
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
End Module
The client and friend client are only different by one line of code:
_client = New TcpClient(extip, port) 'Friend client connects to external IP
_client = New TcpClient(ip, port) 'My client connects to local IP

Your issue is here:
_server = New TcpListener(IPAddress.Parse(ip), port)
The TcpListener(IPAddress, Int32) overload specifies which IP address to accept connections from, meaning it will accept connections from ONLY that IP (in this case your local address).
To fix this you've got to listen for connections at IPAddress.Any (equivalent to 0.0.0.0), which specifies that it should accept connections from any IP address.
_server = New TcpListener(IPAddress.Any, port)

Related

My program can't read an ASCII string from TCP connection, keeps looping

I'm connecting to a specific TCP port of a server, do stuff, and I need to disconnect at some point, then wait for the server to open its port again and reconnect.
My program loops forever.
To disconnect from the server, I sent from the server the string "TCP:OFF" and the close the port (server side). Whenever my program reads this line, I want it to close its connection and wait the server to open its port again. This is because of the TCP/IP protocol.
The problem is that the specific ASCII string sent from my server is not read until I put my mouse over my window (weird). At the end, I want my program to work by itself and minimized, without human intervention.
There must be a problem in the timing of my networkStream reading.
Code
While tcpClient.Connected() = False
Try
tcpClient.ReceiveTimeout = 1000
tcpClient.SendTimeout = 1000
tcpClient.Connect("192.168.10.100", 10003)
Console.WriteLine("Connection OK")
System.Threading.Thread.Sleep(1000)
Catch ex As Exception
Console.WriteLine("ERRORR : Server unreachable")
System.Threading.Thread.Sleep(1000)
End Try
End While
Dim networkStream As NetworkStream = tcpClient.GetStream()
If networkStream.CanRead And networkStream.DataAvailable Then
Try
ReadData = ""
Dim myReadBuffer As Byte() = New Byte(7) {}
Dim numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length)
ReadData = Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead)
Console.Write(ReadData & vbCrLf)
Catch ex As Exception
Console.Write("Error reading data")
End Try
End If
If ReadData = "TCP:OFF" Then
tcpClient.Close()
ReadData = ""
Console.WriteLine("Closing connection")
System.Threading.Thread.Sleep(5000)
tcpClient = New TcpClient
End If
I'm doing a Windows form program in latest Visual Studio.

Reconnect to server after losing connection with Tcp Socket

I tried to use dont linger to reconnect to the server when losing connection
Public Class Agent
Dim bytes(1024) As Byte
Dim remoteEP As New IPEndPoint(IPAddress.Parse(My.Settings("HostIP").ToString), CType(My.Settings("HostPort"), Integer))
Dim permis As New SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "", SocketPermission.AllPorts)
Dim S As New Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
If connect is successful it goeos to getdatadb, if not it goes to socketclose first and then it tries to connect again
Sub Connect()
Try
S.Connect(remoteEP)
Catch ex As Exception
socketclose()
S.Connect(remoteEP)
End Try
GetDataDb()
End Sub
with this to close the socket
Sub socketclose()
Dim myOpts As New LingerOption(True, 1)
S.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, myOpts)
S.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, False)
S.Shutdown(SocketShutdown.Both)
S.Close()
End Sub
but it still shows exception
Once the socket has been disconnected, you can only reconnect again
asynchronously, and only to a different EndPoint. BeginConnect must
be called on a thread that won't exit until the operation has been
completed.
I don't know why dontlinger doesn't work.

Udpclient sometimes throws exception

I'm currently working on a UDP communication PC <-> ARM LM3S6965 (Luminary) through the Ethernet. On the PC there is a VB.net application that simulates a UDP server/client.
the message is broadcasted from Vb.net application to ARM LM3S6965 based device, and in return response is sent from ARM Device to vb.net application.
but sometimes receive UdpClient throws socket exception i.e. Only one usage of each socket address (protocol/network address/port) is normally permitted.
the line which throws exception is
udpReceivingClient = New UdpClient(mnPort)
Complete VB.net Code is as follows
Module mod_Search_UDP
Public mnPort As Int32 = 3040 'Port number to send/recieve data on
'Public Const msBroadcastAddress As String = "255.255.255.255" 'Sends data to all LOCAL listening clients, to send data over WAN you'll need to enter a public (external) IP address of the other client
'Dim endPoint As IPEndPoint = New IPEndPoint(msBroadcastAddress, mnPort)
Public udpReceivingClient As UdpClient 'Client for handling incoming data
Public udpSendingClient As UdpClient 'Client for sending data
Public receivingThread As Thread 'Create a separate thread to listen for incoming data, helps to prevent the form from freezing up
Public mbiClosing As Boolean = False 'Used to close clients if form is closing
Public mbiCloseRxClient As Boolean = False
Public Sub InitializeSender()
Dim soc As Socket
Dim lsPort As String
Dim lnPort As Int32 = 3040
Const lsBroadcastAdd As String = "255.255.255.255"
'Dim endPoint As IPEndPoint = New IPEndPoint(msBroadcastAddress, mnPort)
'udpSendingClient = New UdpClient(endPoint)
udpSendingClient = New UdpClient(lsBroadcastAdd, lnPort)
udpSendingClient.EnableBroadcast = True
soc = udpSendingClient.Client
lsPort = (CType(soc.LocalEndPoint, IPEndPoint).Port.ToString())
mnPort = Convert.ToInt32(lsPort)
End Sub
Public Sub InitializeReceiver()
'Create UdpClient class and bind it to the local port number provided
'Try
udpReceivingClient = New UdpClient(mnPort)
'udpReceivingClient.EnableBroadcast = True
mbiCloseRxClient = True
'Catch ex As Exception
' MsgBox(ex.ToString)
'End Try
Dim start As ThreadStart = New ThreadStart(AddressOf MT_Receiver)
receivingThread = New Thread(start)
receivingThread.IsBackground = True
receivingThread.Start()
End Sub
Public Sub MT_Receiver()
Dim endPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, mnPort) 'Listen for incoming data from any IP address on the specified port
Dim lbData() As Byte 'Buffer for storing incoming bytes
Dim llRet As UInt16
'udpListen.Poll(1000, Net.Sockets.SelectMode.SelectRead)
While (True) 'Setup an infinite loop
If mbiClosing = True Then 'Exit sub if form is closing
Exit Sub
End If
llRet = udpReceivingClient.Available
If llRet > 0 Then
lbData = udpReceivingClient.Receive(endPoint) 'Receive incoming bytes
'If udpListen.Available Then
' udpListen.Receive(lbData, 256, Net.Sockets.SocketFlags.None)
'End If
'If lbData Is Nothing Then
'Else
frmSearchUDP.MT_Validate_Msg(lbData)
End If
End While
End Sub
Public Sub MT_Send_UDP(ByVal lbTxBuffer() As Byte)
InitializeSender()
If mbiCloseRxClient = True Then
receivingThread.Abort()
udpReceivingClient.Client.Dispose()
udpReceivingClient.Close()
End If
Try
udpSendingClient.Send(lbTxBuffer, lbTxBuffer.Length)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
udpSendingClient.Client.Dispose()
udpSendingClient.Close()
InitializeReceiver()
'Try
' udpReceivingClient.BeginReceive(AddressOf MT_RX_Callback, Nothing)
'Catch ex As Exception
' MsgBox(ex.ToString)
'End Try
End Sub
End Module
Whats mistake is there in code ? how can i use same port for receive and transmit ?

Socket program freezes on load

The program freezes on load. At first it was working as it was supposed to, but after I cleaned and built the solution, it only freezes on load. The weird part is that it only freezes and it does not show the exception message for the catch.
here is the class file I used
Imports System.Net ' for IPAddress
Imports System.Net.Sockets 'for TcpListener
Public Class clientSocket
Dim aString As String
Dim port As Integer 'this is the port number
Dim localAddr As IPAddress ' this is the IP address
Dim client As TcpClient ' This is for the TCP/IP Protocol
Dim clientListener As TcpListener
Public Function startSocket() As String
Try
'define the two values for your Server
port = 1234
localAddr = IPAddress.Loopback 'loopbak = 127.0.0.1 = myself
clientListener = New TcpListener(localAddr, 4321)
client = New TcpClient(localAddr.ToString, port)
Return "Connected to the server"
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Function receive() As String
Try
clientListener.Start()
Dim mySocket As Socket
mySocket = clientListener.AcceptSocket()
Dim recieveBuff(225) As Byte
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
Dim str As String = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))
Return str
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
str = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))
clientListener.Stop()
Catch exp As Exception
Return "Exception: " + exp.Message
End Try
End Function
End Class
Or use BeginAcceptSocket, but you'll have to move your receive code to the callback.
mySocket = clientListener.AcceptSocket()
These lines block further action untill a socket has been acepted, it will block your code until a socket has been accepted. Use thread to prevent blocking

Check if port 57875 is closed on localhost VB.Net?

I am trying to see if port 57875 on localhost, the computer, is closed.
Here is the code I have so far:
Try
Dim checkPort As TcpClient = New TcpClient("localhost", 57875)
Catch ex As Exception
MsgBox("WARNING: Port 57875 is not forwarded ! The game will probably encounter an error !")
End Try
Even if it is forwarded, it will think it isn't. What is wrong with the code?
Here you have an example:
Dim host As String = "localhost"
Dim port As Integer = 57875
Dim addr As IPAddress = DirectCast(Dns.GetHostAddresses(host)(0), IPAddress)
Try
Dim tcpList As New TcpListener(addr, port)
tcpList.Start()
Catch sx As SocketException
'Catch exception - No available port
End Try