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
Related
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)
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.
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.
I have a TCP server made in java and I want to connect to Visual Basic. I have the following code
Try
clientSocket.Connect("192.168.1.64", 4444)
Label1.Text = "Cliente Conectado"
Catch ex As Exception
Label1.Text = ex.ToString
End Try
Dim TCPNetworkStream As NetworkStream = clientSocket.GetStream
Dim TCPStreamWriter As New StreamWriter(TCPNetworkStream)
TCPStreamWriter.Write(TextBox2.Text)
TCPStreamWriter.Close()
'TCPNetworkStream.Close()
'clientSocket.Close()
how can i get the text from the server?
You have to read from the network stream using NetworkStream.Read.
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