How to read message TCP server in Visual Basic. NET? - vb.net

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.

Related

How to test SMTP connection before SMTPClient.Send [VB.NET]

Pretty new to programming here.
The program I'm currently working on needs to send an email with logs.
Working great if I'm using the right server host but when I'm trying with a "false" server host my program sure can't connect, but it immediatly crash, I can't raise any exception, can't tell the user he's doing something wrong, nothing.
So I guess I have to test the connection before SMTPClient.Send but I can't seem to find how...
How can I test a SMTP Server connection in VB.NET ?
That's what I'm using :
Try
Dim SmtpServer As New SmtpClient()
With SmtpServer
.EnableSsl = False
.UseDefaultCredentials = False
.Credentials = New Net.NetworkCredential(MailUser, MailPassword)
.Port = 25
.Host = ServerAdress
End With
Dim mail As New MailMessage()
With mail
.From = New MailAddress(MailSender)
.To.Add(MailReceiver)
.CC.Add(MailCC)
.Subject = MailObject
.Body = MailBody
End With
SmtpServer.Send(mail)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
1- I think you should try something like this:
Using tcp As New TcpClient
Try
tcp.Connect(ip, 25)
' server found
Catch ex As Exception
' server not found
End Try
tcp.Close()
End Using ' tcpclient
2- For test your smtp server this article can be usefull:
https://www.port25.com/how-to-check-an-smtp-connection-with-a-manual-telnet-session-2/
3- and also there is a smtp test class in this question's answers
.Net TcpClient and SmtpClient won't connect to my Smtp server

TCP Client program won't connect to my server

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)

VB.NET: How can you get the SQL server name and instance name in Windows 10?

This startup form is used for getting the SQL Server name and instance name:
Private Sub GetServerList()
Try
Dim Server As String = String.Empty
Dim instance As SqlDataSourceEnumerator = SqlDataSourceEnumerator.Instance
Dim cmbServers = New ComboBox
Dim table As DataTable = instance.GetDataSources()
For Each row As DataRow In table.Rows
Server = String.Empty
Server = row("ServerName")
If row("InstanceName").ToString.Length > 0 Then
Server = Server & "\" & row("InstanceName")
End If
cmbServers.Items.Add(Server)
Next
cmbServers.SelectedIndex = cmbServers.FindStringExact(Environment.MachineName)
My.Settings.ServerName = cmbServers.Text
My.Settings.Save()
Catch ex As Exception
MessageBox.Show("Cannot connect to the Server", "SMALLER", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End Sub
The main problem is that no server name nor instance name is being displayed in the ComboBox, I've checked it myself using Msgbox(cmbServers.Text) the result is blank. While for other versions of Windows (7, 8, 8.1) there are no issues...
I've read a similar post regarding this as well, one of the solutions states that you must enable the SQL Server Browser service, I've turned the said service on, but still no luck...

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.

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