No connection could be made because the target machine actively refuse it
-
Monday, March 05, 2012 1:32 AM
I have my tcplistener on port 5000, 127.0.0.1 as the ip and when i connect using my internal ip, 192.168.1.141 it "refuses the connection", same with the external but if i connect using 127.0.0.1 it works. how do i fix this?
by the way here's my code:
'server:
Imports System.Text Imports System.Threading Imports System.Net.Sockets Imports System.Net Public Class Server Dim server As TcpListener Dim receiver As Thread Dim client As New TcpClient() Dim connection As NetworkStream Dim stopper As Thread Dim starter As Thread Dim restarter As Thread Dim WithEvents t As Windows.Forms.Timer = New Windows.Forms.Timer Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click Dim reply As Byte() = Encoding.ASCII.GetBytes(TextBox1.Text & vbNewLine) connection.Write(reply, 0, reply.Length) TextBox1.Text = "" Console.Text &= ("System> Sent" & vbNewLine) End Sub Sub start() server = New TcpListener(IPAddress.Parse("127.0.0.1"), 5000) server.Start() Console.Text &= ("System> Server Started" & vbNewLine) stopper = New Thread(AddressOf halt) receiver = New Thread(AddressOf awaitClient) receiver.Start() End Sub Sub restart() server.Stop() connection.Dispose() receiver.Abort() starter.Abort() server = New TcpListener(IPAddress.Parse("127.0.0.1"), 5000) server.Start() Console.Text &= ("System> Server Started" & vbNewLine) stopper = New Thread(AddressOf halt) receiver = New Thread(AddressOf awaitClient) receiver.Start() End Sub Sub awaitClient() Console.Text &= ("System> Waiting for client" & vbNewLine) client = Server.AcceptTcpClient connection = client.GetStream() Console.Text &= ("System> Client Connected" & vbNewLine) t.Start() fetch() End Sub Sub Beep() My.Computer.Audio.Play(My.Resources.beeper, AudioPlayMode.Background) End Sub Sub fetch() Try Do Dim commandPacket(1492) As Byte connection.Read(commandPacket, 0, 1492) Dim commandText As String = Encoding.ASCII.GetString(commandPacket) Dim command() As String = Split(commandText, "*") If command(0) = 1 Then Beep() ElseIf command(0) = 2 Then Dim tempString As String = "Client> " & command(1) Console.Text &= (tempString & vbNewLine) ElseIf command(0) = 3 Then Console.Text &= ("System> Connection Closed" & vbNewLine) restarter = New Thread(AddressOf restart) restarter.Start() End If Loop Catch ex As Exception If ex.Message.Contains("Conversion from string") = False Or ex.Message.Contains("Thread was being aborted.") = False Then Console.Text &= "System> ERROR:" & ex.Message.ToString & vbNewLine End If End Try awaitClient() End Sub Sub halt() If client.Connected Then server.Stop() connection.Dispose() receiver.Abort() restarter.Abort() starter.Abort() Console.Text &= ("System> Connection Closed" & vbNewLine) End If End Sub Private Sub Server_Closed(sender As System.Object, e As System.EventArgs) Handles MyBase.FormClosed If client.Connected Then server.Stop() connection.Dispose() receiver.Abort() restarter.Abort() starter.Abort() Console.Text &= ("System> Connection Closed" & vbNewLine) End If End End Sub Private Sub Server_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load Control.CheckForIllegalCrossThreadCalls = False starter = New Thread(AddressOf start) starter.Start() t.Start() End Sub Sub t_Tick(sender As Object, e As EventArgs) Handles t.Tick If client.Connected Then Button1.Enabled = True Else Button1.Enabled = False End If End Sub End Class
'client: Imports System.Net Imports System.Net.Sockets Imports System.Text Imports System.Threading Public Class Form1 Dim server As New TcpClient() Dim connection As NetworkStream Dim recieveMsg As New Thread(AddressOf rm) Sub rm() Do While server.Connected Dim packet(1492) As Byte connection.Read(packet, 0, 1492) TextBox1.Text &= "Host> " & Encoding.ASCII.GetString(packet) & vbNewLine Loop End Sub Private Sub Connect(sender As System.Object, e As System.EventArgs) Handles Button3.Click Control.CheckForIllegalCrossThreadCalls = False server.Connect(IpAddressInput1.Text, 5000) connection = server.GetStream() TextBox1.Text &= "System> Connected" & vbNewLine Button3.Enabled = False IpAddressInput1.Enabled = False recieveMsg.Start() End Sub Private Sub SendMessage(sender As System.Object, e As System.EventArgs) Handles Button2.Click command("2*" & TextBox2.Text & vbNewLine) TextBox1.Text &= "System> sent" & vbNewLine TextBox2.Text = "" End Sub Private Sub Beep(sender As System.Object, e As System.EventArgs) Handles Button1.Click command("1") End Sub Sub command(ByVal instruction As String) Dim packet() As Byte = Encoding.ASCII.GetBytes(instruction) Try connection.Write(packet, 0, packet.Length) Catch ex As Exception TextBox1.Text &= "System> ERROR:" & ex.Message.ToString & vbNewLine TextBox1.Text &= "System> Disconnected" & vbNewLine connection.Dispose() End Try End Sub Private Sub Form1_Closed(sender As System.Object, e As System.EventArgs) Handles MyBase.FormClosed recieveMsg.Abort() If server.Connected Then command("3") connection.Dispose() End If End Sub End Class
I'm sorry if I misspelled something or my grammar is wrong, I've never done well in those subjects.
- Edited by Timberwolf Programmers Monday, March 05, 2012 1:34 AM
All Replies
-
Monday, March 05, 2012 11:24 AMYou still haven't removed the lines "Control.CheckForIllegalCrossThreadCalls = False", and you still haven't enable Option Strict On. I can't compile and test it.
Armin
-
Monday, March 05, 2012 11:31 AM
TCP listing is something I don't like (you are always blocked by firewalls or whatever). But what I know is that if this kind of actions on internal Lan's (your ip range) are refused it is mostly cause of the firewall or virusscanner which refuses a certain port.
It was standard set in past in Mc Afee, I don't know the current situation with the later one.
Probably you get for going around this a better answer in the technet forums, those guys and girls have always to do with this kind of settings.
http://technet.microsoft.com/forums
Success
Cor- Edited by Cor LigthertMVP Monday, March 05, 2012 11:32 AM
-
Monday, March 05, 2012 12:13 PM
Due tue the obvious problems mentioned, I didn't analyze your code further so far. I had a closer look at it now:
This kind of exception handling is horrible:
Catch ex As Exception If ex.Message.Contains("Conversion from string") = False Or ex.Message.Contains("Thread was being aborted.") = False Then Console.Text &= "System> ERROR:" & ex.Message.ToString & vbNewLine End If End TryYou can't rely on the message of a String. Not only because it doesn't work here because I get German messages. Instead you should catch different types of Exceptions, like
Catch ex as InvalidOperationException '... handle this type of exception Catch ex as NullReferenceException 'EXAMPLE only '... handle this type of exception catch ex as Exception '... handle all remaining Exceptions End TryIn addition, in your code, you're simply ignoring all exceptions that don't contain a certain text.
It's also not required to write
ex.Message.ToString
because ex.Message is already a String.You should also start giving everything speaking names. It's hard to find out what "Textbox1" contains or what sub "RM" does.
Then you have these two lines:
netStream.Read(packet, 0, 1492) TextBox1.Text &= "Host> " & Encoding.ASCII.GetString(packet) & vbNewLineWhy do you ignore the return value of the Read function? You must convert only the part of the buffer that has been filled, not the whole buffer.
Look at these two lines:
Dim commandPacket(1492) As Byte connection.Read(commandPacket, 0, 1492)Note that you specify the upper bound of the array. As the lower bound is 0, the total number of items is 1493 whereas you specify 1492 as the size of the buffer.
Armin
- Edited by Armin Zingler Monday, March 05, 2012 12:14 PM
-
Monday, March 05, 2012 12:26 PM
More...:
- You are recursively calling Sub awaitclient and sub fetch which ends in a stack overflow.
- The "End" statement in form_close is not required.
- Why do you execute Sub Start in a new thread? It has no blocking function call and exits immediatelly, so you don't need an extra thread for it.
EDIT:
- Sub halt is never executed because thread "stopper" is never started.
- When closing the Form, you're stopping the listeners and other threads only if there is a connection.
- Why are you using a Timer to set Button1.enabled? You can set the property whenever a connection is made or lost.
- If a message is sent, you're appending CRLF to the message, and you're adding another CRLF for displaying the message.
- Instead of Abort-ing threads you should implement a controlled end of a thread.
- I don't see the purpose of the "restarter" Thread.
- In Sub rm, you must check if the count of received byts is zero in order to handle the server closing the connection.
Armin
- Edited by Armin Zingler Monday, March 05, 2012 1:12 PM
-
Monday, March 05, 2012 11:24 PM
If I REMOVE Control.CheckForIllegalCrossThreadCalls = False it CREATES an UNNECESSARY ERROR:
Cross-thread operation not valid: Control 'Console' accessed from a thread other than the thread it was created on.
FOR it WORKS with it but NOT WITHOUT it!
Edited Server:
Imports System.Text Imports System.Threading Imports System.Net.Sockets Imports System.Net Public Class Server Dim server As TcpListener Dim receiver As Thread Dim client As New TcpClient() Dim connection As NetworkStream Dim stopper As Thread Dim starter As Thread Dim restarter As Thread Dim WithEvents t As Windows.Forms.Timer = New Windows.Forms.Timer Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click Dim reply As Byte() = Encoding.ASCII.GetBytes(TextBox1.Text & vbNewLine) connection.Write(reply, 0, reply.Length) TextBox1.Text = "" Console.Text &= ("System> Sent" & vbNewLine) End Sub Sub start() server = New TcpListener(IPAddress.Parse("127.0.0.1"), 5000) server.Start() Console.Text &= ("System> Server Started" & vbNewLine) stopper = New Thread(AddressOf halt) receiver = New Thread(AddressOf awaitClient) receiver.Start() End Sub Sub restart() server.Stop() connection.Dispose() receiver.Abort() starter.Abort() server = New TcpListener(IPAddress.Parse("127.0.0.1"), 5000) server.Start() Console.Text &= ("System> Server Started" & vbNewLine) stopper = New Thread(AddressOf halt) receiver = New Thread(AddressOf awaitClient) receiver.Start() End Sub Sub awaitClient() Console.Text &= ("System> Waiting for client" & vbNewLine) client = Server.AcceptTcpClient connection = client.GetStream() Console.Text &= ("System> Client Connected" & vbNewLine) t.Start() fetch() End Sub Sub Beep() My.Computer.Audio.Play(My.Resources.beeper, AudioPlayMode.Background) End Sub Sub fetch() Try Do Dim commandPacket(1492) As Byte connection.Read(commandPacket, 0, 1492) Dim commandText As String = Encoding.ASCII.GetString(commandPacket) Dim command() As String = Split(commandText, "*") If command(0) = 1 Then Beep() ElseIf command(0) = 2 Then Dim tempString As String = "Client> " & command(1) Console.Text &= (tempString & vbNewLine) ElseIf command(0) = 3 Then Console.Text &= ("System> Connection Closed" & vbNewLine) restarter = New Thread(AddressOf restart) restarter.Start() End If Loop Catch ex As Exception If ex.Message.Contains("Conversion from string") = False Or ex.Message.Contains("Thread was being aborted.") = False Then Console.Text &= "System> ERROR:" & ex.Message.ToString & vbNewLine End If stopper = New Thread(AddressOf halt) stopper.Start() End Try awaitClient() End Sub Sub halt() If client.Connected Then server.Stop() connection.Dispose() receiver.Abort() restarter.Abort() starter.Abort() Console.Text &= ("System> Connection Closed" & vbNewLine) End If restarter = New Thread(AddressOf restart) restarter.Start() End Sub Private Sub Server_Closed(sender As System.Object, e As System.EventArgs) Handles MyBase.FormClosed If client.Connected Then server.Stop() connection.Dispose() receiver.Abort() restarter.Abort() starter.Abort() Console.Text &= ("System> Connection Closed" & vbNewLine) End If End End Sub Private Sub Server_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load Control.CheckForIllegalCrossThreadCalls = False starter = New Thread(AddressOf start) starter.Start() t.Start() End Sub Sub t_Tick(sender As Object, e As EventArgs) Handles t.Tick If client.Connected Then Button1.Enabled = True Else Button1.Enabled = False End If End Sub End ClassOh and on the subject of Option Strict On it won't allow me to do this:
If command(0) = 1 Then Beep() ElseIf command(0) = 2 Then Dim tempString As String = "Client> " & command(1) Console.Text &= (tempString & vbNewLine) ElseIf command(0) = 3 Then Console.Text &= ("System> Connection Closed" & vbNewLine) restarter = New Thread(AddressOf restart) restarter.Start() End Ifand without it like that it won't work.
I'm sorry if I misspelled something or my grammar is wrong, I've never done well in those subjects.
- Edited by Timberwolf Programmers Monday, March 05, 2012 11:32 PM
-
Monday, March 05, 2012 11:46 PM
If I REMOVE Control.CheckForIllegalCrossThreadCalls = False it CREATES an UNNECESSARY ERROR:
No, this is not an unnecessary error. It happens to work. It's like crossing a red light - you might survive, but you shouldn't do it. It is not allowed to access a control from a different thread. This is true for every windows application, so you should accept it. That's not only my personal opinion, it's a fact.
- "Oh and on the subject of Option Strict On it won't allow me to do this:"
If you don't start becoming aware of data types and their appropriate handling, your code is open for all kinds of errors and unexpected behavior. Most people won't start helping if the code is not even compilable.
Look at the data type of variable 'Command'. It's an array of Strings. You are comparing an item of the array to a number. You must not compare a String to a number. A String is a sequence of UTF-16 encoded Unicode code points, whereas a number (Integer) is a binary encoded value. Simply compare to the Strings "1", "2" and "3" and the problem is correctly solved.
Armin
- Edited by Armin Zingler Monday, March 05, 2012 11:47 PM
-
Tuesday, March 06, 2012 12:07 AMBut when I did that and turned on Strict from the last thread I posted it FAILED EPICALLY! It would not recognize any of the commands, I don't know why but it didn't. I got my code from a friend who has a working reverse version. He tried his best to "convert" it to a non-reverse but so far it has failed.
I'm sorry if I misspelled something or my grammar is wrong, I've never done well in those subjects.
-
Tuesday, March 06, 2012 12:43 AM
If you want to make it work correctly, you must marshal the access to the UI thread by calling the control's BeginInvoke method.
Add this code:
Private Delegate Sub AppendToConsoleDelegate(ByVal Text As String) Private ReadOnly AppendToConsoleFunction As New AppendToConsoleDelegate(AddressOf UIAppendToConsole) Private Sub UIAppendToConsole(ByVal Text As String) Console.Text &= Text End Sub Private Sub AppendToConsole(ByVal Text As String) Console.BeginInvoke(AppendToConsoleFunction, Text) End SubIn addition, wherever you are currently appending text to the textbox name 'console' from another thread, you must now call AppendToConsole. For example, instead of writing
Console.Text &= ("System> Sent" & vbNewLine)you call
AppendToConsole("System> Sent" & vbNewLine)
If I had the choice, I would separate the UI (the Form) from the rest, but I don't want you to rewrite what you already have. Maybe later you will see that splitting it into separate classes will give a better overview. Anyway, if you do the changes just mentioned, the InvalidOperationExceptions should be gone.
Armin
-
Tuesday, March 06, 2012 12:53 AMwhat about the problem with the If Command(0) = 1 vs. If Command(0) = "1"
I'm sorry if I misspelled something or my grammar is wrong, I've never done well in those subjects.
-
Tuesday, March 06, 2012 12:54 AM
what about the problem with the If Command(0) = 1 vs. If Command(0) = "1"
Doesn't the latter version work? Here it does.
Armin
- Edited by Armin Zingler Tuesday, March 06, 2012 12:54 AM
-
Tuesday, March 06, 2012 12:59 AMI'll try it again
I'm sorry if I misspelled something or my grammar is wrong, I've never done well in those subjects.
-
Tuesday, March 06, 2012 1:06 AM
Ok, my new code is:
Option Strict On Imports System.Text Imports System.Threading Imports System.Net.Sockets Imports System.Net Public Class Server Dim server As TcpListener Dim receiver As Thread Dim client As New TcpClient() Dim connection As NetworkStream Dim stopper As Thread Dim starter As Thread Dim restarter As Thread Dim WithEvents t As Windows.Forms.Timer = New Windows.Forms.Timer Private Delegate Sub AppendToConsoleDelegate(ByVal Text As String) Private ReadOnly AppendToConsoleFunction As New AppendToConsoleDelegate(AddressOf UIAppendToConsole) Private Sub UIAppendToConsole(ByVal Text As String) Console.Text &= Text End Sub Private Sub AppendToConsole(ByVal Text As String) Console.BeginInvoke(AppendToConsoleFunction, Text) End Sub Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click Dim reply As Byte() = Encoding.ASCII.GetBytes(TextBox1.Text & vbNewLine) connection.Write(reply, 0, reply.Length) TextBox1.Text = "" AppendToConsole("System> Sent" & vbNewLine) End Sub Sub start() server = New TcpListener(IPAddress.Parse("127.0.0.1"), 5000) server.Start() AppendToConsole("System> Server Started" & vbNewLine) stopper = New Thread(AddressOf halt) receiver = New Thread(AddressOf awaitClient) receiver.Start() End Sub Sub restart() server.Stop() connection.Dispose() receiver.Abort() starter.Abort() server = New TcpListener(IPAddress.Parse("127.0.0.1"), 5000) server.Start() AppendToConsole("System> Server Started" & vbNewLine) stopper = New Thread(AddressOf halt) receiver = New Thread(AddressOf awaitClient) receiver.Start() End Sub Sub awaitClient() AppendToConsole("System> Waiting for client" & vbNewLine) client = Server.AcceptTcpClient connection = client.GetStream() AppendToConsole("System> Client Connected" & vbNewLine) t.Start() fetch() End Sub Sub Beep() My.Computer.Audio.Play(My.Resources.beeper, AudioPlayMode.Background) End Sub Sub fetch() Try Do Dim commandPacket(1492) As Byte connection.Read(commandPacket, 0, 1492) Dim commandText As String = Encoding.ASCII.GetString(commandPacket) Dim command() As String = Split(commandText, "*") If command(0) = "1" Then Beep() ElseIf command(0) = "2" Then Dim tempString As String = "Client> " & command(1) AppendToConsole(tempString & vbNewLine) ElseIf command(0) = "3" Then AppendToConsole("System> Connection Closed" & vbNewLine) restarter = New Thread(AddressOf restart) restarter.Start() End If Loop Catch ex As Exception If ex.Message.Contains("Conversion from string") = False Or ex.Message.Contains("Thread was being aborted.") = False Then AppendToConsole("System> ERROR:" & ex.Message.ToString & vbNewLine) End If stopper = New Thread(AddressOf halt) stopper.Start() End Try awaitClient() End Sub Sub halt() If client.Connected Then server.Stop() connection.Dispose() receiver.Abort() restarter.Abort() starter.Abort() AppendToConsole("System> Connection Closed" & vbNewLine) End If restarter = New Thread(AddressOf restart) restarter.Start() End Sub Private Sub Server_Closed(sender As System.Object, e As System.EventArgs) Handles MyBase.FormClosed If client.Connected Then server.Stop() connection.Dispose() receiver.Abort() restarter.Abort() starter.Abort() AppendToConsole("System> Connection Closed" & vbNewLine) End If End End Sub Private Sub Server_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load starter = New Thread(AddressOf start) starter.Start() t.Start() End Sub Sub t_Tick(sender As Object, e As EventArgs) Handles t.Tick If client.Connected Then Button1.Enabled = True Else Button1.Enabled = False End If End Sub End Class
Option Strict On Imports System.Net Imports System.Net.Sockets Imports System.Text Imports System.Threading Public Class Client Dim server As New TcpClient() Dim connection As NetworkStream Dim recieveMsg As New Thread(AddressOf rm) Private Delegate Sub AppendToConsoleDelegate(ByVal Text As String) Private ReadOnly AppendToConsoleFunction As New AppendToConsoleDelegate(AddressOf UIAppendToConsole) Private Sub UIAppendToConsole(ByVal Text As String) TextBox1.Text &= (Text) End Sub Private Sub AppendToConsole(ByVal Text As String) TextBox1.BeginInvoke(AppendToConsoleFunction, Text) End Sub Sub rm() Do While server.Connected Dim packet(1492) As Byte connection.Read(packet, 0, 1492) AppendToConsole("Host> " & Encoding.ASCII.GetString(packet) & vbNewLine) Loop End Sub Private Sub Connect(sender As System.Object, e As System.EventArgs) Handles Button3.Click Try server.Connect(IpAddressInput1.Text, 5000) connection = server.GetStream() AppendToConsole("System> Connected" & vbNewLine) Button3.Enabled = False IpAddressInput1.Enabled = False recieveMsg.Start() Catch ex As Exception AppendToConsole("System> ERROR:" & ex.Message.ToString & vbNewLine) End Try End Sub Private Sub SendMessage(sender As System.Object, e As System.EventArgs) Handles Button2.Click command("2*" & TextBox2.Text & vbNewLine) AppendToConsole("System> sent" & vbNewLine) TextBox2.Text = "" End Sub Private Sub Beep(sender As System.Object, e As System.EventArgs) Handles Button1.Click command("1") End Sub Sub command(ByVal instruction As String) Dim packet() As Byte = Encoding.ASCII.GetBytes(instruction) Try connection.Write(packet, 0, packet.Length) Catch ex As Exception AppendToConsole("System> ERROR:" & ex.Message.ToString & vbNewLine) AppendToConsole("System> Disconnected" & vbNewLine) connection.Dispose() End Try End Sub Private Sub Form1_Closed(sender As System.Object, e As System.EventArgs) Handles MyBase.FormClosed recieveMsg.Abort() If server.Connected Then command("3") connection.Dispose() End If End Sub End Class
but I still give me the actively refused it error.I'm sorry if I misspelled something or my grammar is wrong, I've never done well in those subjects.
-
Tuesday, March 06, 2012 1:17 AM
For that part, look at Cor's message (regardig the firewall issue). Try sending a ping. Anyway, it's not a VB problem.but I still give me the actively refused it error.
Armin
-
Tuesday, March 06, 2012 1:30 AMI let it through my firewall, it still actively refused it and I can't find anything in my AV program on ports and stuff, I have MS Security Essentials.
I'm sorry if I misspelled something or my grammar is wrong, I've never done well in those subjects.
-
Tuesday, March 06, 2012 1:39 AM
In the following line, the server must listen at the same address as the client is connecting to:
server = New TcpListener(IPAddress.Parse("127.0.0.1"), 5000)
If the client wants to connect to 192.168.1.141, the server must listen at the same address.
Armin
-
Tuesday, March 06, 2012 2:04 AM
-
Tuesday, March 06, 2012 12:27 PM
Darnhold,
Like I wrote some viruscheckers also refuse some ports to be used.
Not really a developers question to solve in my idea.
Success
Cor -
Tuesday, March 06, 2012 12:37 PM
Did you try it?In the following line, the server must listen at the same address as the client is connecting to:
server = New TcpListener(IPAddress.Parse("127.0.0.1"), 5000)
If the client wants to connect to 192.168.1.141, the server must listen at the same address.
Armin
-
Friday, September 14, 2012 5:35 PM
project abandonedI'm sorry if I misspelled something or my grammar is wrong, I've never done well in those subjects.
- Marked As Answer by Timberwolf Programmers Friday, September 14, 2012 5:35 PM

