|
-
Jan 12th, 2011, 07:02 PM
#1
Thread Starter
Junior Member
Socket connection error
Hello.
I'm having an error in a server-client application I made using arrays. I don't exactly know what the problem is, but it's something like the second socket and higher don't connect to the listener. (?)
Here is my server code:
Code:
Public Class Form1
Dim max_players As Integer = 0
Dim tcp_listener() As System.Net.Sockets.TcpListener
Dim socket() As System.Net.Sockets.Socket
Dim network_stream As System.Net.Sockets.NetworkStream
Dim streamreader As System.IO.StreamReader
Dim serving As Boolean = False
Dim player_connected() As Boolean
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If serving = False Then
Dim slots As Integer = Replace(TextBox1.Text, " ", Nothing)
If IsNumeric(slots) Then
If slots > 0 And slots < 11 Then
serving = True
Button1.Text = "Serving..."
Dim start_port As Integer = 21760
max_players = slots
ReDim socket(max_players)
ReDim tcp_listener(max_players)
ReDim player_connected(max_players)
For a As Integer = 0 To max_players - 1
player_connected(a) = False
tcp_listener(a) = New System.Net.Sockets.TcpListener(start_port)
tcp_listener(a).Start()
start_port = start_port + 1
Timer1.Start()
Timer5.Start()
Next
Dim thread As New System.Threading.Thread(AddressOf Listen)
thread.Start()
End If
End If
End If
End Sub
' I added these test_connected booleans, these msgboxes and changed some things so I could trap the error as I was trying to chat with a friend of mine (two connections). Didn't work as well :(
Dim test1_connected As Boolean = False
Dim test2_connected As Boolean = False
Private Sub Listen()
Do While serving = True
For a As Integer = 0 To max_players - 1
If test1_connected = True And test2_connected = True Then
MsgBox("0")
'Exit Sub
Else
If test1_connected = False Then
MsgBox("1")
socket(0) = tcp_listener(0).AcceptSocket()
test1_connected = True
network_stream = New System.Net.Sockets.NetworkStream(socket(0))
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes("connection1|")
network_stream.Write(data, 0, data.Length)
Else
MsgBox("2")
socket(1) = tcp_listener(1).AcceptSocket()
MsgBox("yes123")
test2_connected = True
network_stream = New System.Net.Sockets.NetworkStream(socket(1))
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes("connection1|")
network_stream.Write(data, 0, data.Length)
'Exit For
End If
End If
'network_stream = New System.Net.Sockets.NetworkStream(socket(a))
'Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes("connection1|")
'network_stream.Write(data, 0, data.Length)
Next
Loop
End Sub
End Class
Client code:
Code:
Dim connecting As Boolean = False
Dim tcp_client As System.Net.Sockets.TcpClient
Dim current_port As Integer = "21760"
Dim network_stream As System.Net.Sockets.NetworkStream
Private Sub Connect(ByVal port As Integer)
Try
current_port = port
tcp_client = New System.Net.Sockets.TcpClient
tcp_client.Connect("ip.ip.ip.ip", port)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If connecting = False Then
connecting = True
Button1.Text = "Connecting..."
TextBox1.ReadOnly = True
username = TextBox1.Text
tcp_client = New System.Net.Sockets.TcpClient
Dim thread As New System.Threading.Thread(AddressOf Connect)
thread.Start(current_port)
Timer4.Start()
Else
MsgBox("Connection failed.", MsgBoxStyle.Critical, "Error")
End If
End Sub
Private Sub Timer4_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer4.Tick
If tcp_client.Connected = True Then
Timer4.Stop()
Else
If connecting = True Then
Me.Text = Me.Text & "123"
If current_port = "21760" Then ' max port number
connecting = False
End If
Dim thread As New System.Threading.Thread(AddressOf Connect)
thread.Start(current_port + 1)
Timer4.Stop()
Timer4.Start()
Else
Button1.Text = "Connect"
TextBox1.ReadOnly = False
Timer4.Stop()
MsgBox("Connection timeout.", MsgBoxStyle.Critical, "Error")
End If
End If
End Sub
End Class
Thanks.
Last edited by 1246; Jan 16th, 2011 at 10:01 AM.
-
Jan 13th, 2011, 12:43 AM
#2
Re: Socket connection error
It looks like you have all the listeners listening on the same port. If the port is opened and used by one listener object, I am not sure you could use it for another listener object.
Without knowing exactly what you are trying to achieve, it's hard to tell, but I am guessing the design of your app can be improved. If you are going to use just one port, instead of maintaining an array of listeners, create a thread that listens onto the specific port and alerts the application whenever any data is received on that port.
.
-
Jan 13th, 2011, 12:06 PM
#3
Thread Starter
Junior Member
Re: Socket connection error
 Originally Posted by honeybee
It looks like you have all the listeners listening on the same port. If the port is opened and used by one listener object, I am not sure you could use it for another listener object.
Without knowing exactly what you are trying to achieve, it's hard to tell, but I am guessing the design of your app can be improved. If you are going to use just one port, instead of maintaining an array of listeners, create a thread that listens onto the specific port and alerts the application whenever any data is received on that port.
.
If you look closely you will see that I create a variable start_port which contains the port for the first listener and then in the For Loop it keeps increasing to each listener.
I don't think anybody needs to know but I am trying to make a 2D online game.
I had all working but I wanted to make the game work without the runtime winsock files (before I was using winsock) so I moved to sockets and tcp listeners. Until here, all okay.
But then I also wanted to make it so I didn't have to copy&paste the player info for each player I wanted. So I made it using arrays. The problem is in the connection or listening part.
And I will use the same ports as the slots number, which can be 1, 2, 3...
-
Jan 13th, 2011, 05:00 PM
#4
Thread Starter
Junior Member
Re: Socket connection error
Bump.
+10 threads have been created since mine and all of them got answered more than once.
-
Jan 13th, 2011, 05:19 PM
#5
Re: Socket connection error
What do you really expect? You haven't told us what error message you are getting, or even if you are getting an error message. You only say that there is an error in your application. You even suggest that you don't know what the error is. Do you know what it is doing that it should not be doing? Do you know what it is not doing that it should be doing? Throw us a bone here. Heck, I'm impressed that HB rooted through all that code looking for nobody knows what just enough to get even that comment.
The typical way to work with TCP would be to listen on a port, then when you get a client request you would spin off a thread to handle that request, during which the listener goes back to listening. On the other hand, the last time I was working with games, they were using UDP rather than TCP, so there weren't even connections. Online may be different, though.
My usual boring signature: Nothing
 
-
Jan 13th, 2011, 05:24 PM
#6
Thread Starter
Junior Member
Re: Socket connection error
I am not getting any error message.
What I wanted was that someone copied my code and pasted it in a VB application and try it out.
Also, as I told, the first socket connects perfectly, the problem is with the next.
-
Jan 13th, 2011, 06:18 PM
#7
Re: Socket connection error
Yes, but you haven't said what the problem is. You are leaving it up to us to test your code, guess at what the problem is, figure out the answer and reply. Oddly, somebody might actually do that, now that you have stated what it is you want.
Having had a glance at it, there are many things worth fixing. First thing to try is turning Option Strict ON, as it will cause you to fix a few bugs and will make the code faster.
I notice that you are creating an array of listeners and starting them all off. You then go into a thread that appears to run a nearly perpetual loop. This seems woefully inefficient, as it seems like it would peg one CPU core regardless of whether or not there was any traffic, but inside that loop you run another loop from 0 to max players. That doesn't surprise me, but you then only deal with listener(0) and listener(1). What happened to all the other listeners? It seems like you never deal with them again after starting them listening.
You also get a socket back. I realize that you are more familiar with sockets, but .NET deals more in TCPClient objects, so you might consider moving in that direction.
I haven't worked with TCP in a long time, but doesn't that raise an event or something when a client requests a connection, thereby removing the need for that servicing loop?
My usual boring signature: Nothing
 
-
Jan 13th, 2011, 06:50 PM
#8
Thread Starter
Junior Member
Re: Socket connection error
 Originally Posted by Shaggy Hiker
Having had a glance at it, there are many things worth fixing. First thing to try is turning Option Strict ON, as it will cause you to fix a few bugs and will make the code faster.
That causes +10 errors in the code.
I notice that you are creating an array of listeners and starting them all off. You then go into a thread that appears to run a nearly perpetual loop. This seems woefully inefficient, as it seems like it would peg one CPU core regardless of whether or not there was any traffic, but inside that loop you run another loop from 0 to max players. That doesn't surprise me, but you then only deal with listener(0) and listener(1). What happened to all the other listeners? It seems like you never deal with them again after starting them listening.
That's because I was having the past error so I wanted to try it to only allow the first and second connections but it didn't work. It normally is to be an array to max_players. I will change that when this issue gets solved but I can't solve it by myself so I posted in here.
You also get a socket back. I realize that you are more familiar with sockets, but .NET deals more in TCPClient objects, so you might consider moving in that direction.
Then networkstream won't work as it is an array. At least I didn't manage it to as I did try with tcpclient.
I haven't worked with TCP in a long time, but doesn't that raise an event or something when a client requests a connection, thereby removing the need for that servicing loop?
I don't THINK so.
What happens when I run server and client:
The server starts serving.
First client connects - all okay, server sends check data, client receives and sends back answer.
Second client connects - nothing appears, no data is sent.
-
Jan 13th, 2011, 07:19 PM
#9
Re: Socket connection error
Yes, turning Option Strict ON will create MANY compilation errors until you form better habits. What leaving it off allows you to do is make implicit conversions. These can lead to very subtle bugs, but the biggest single problem is that it makes your code slower. In your case, for what you are doing, that penalty is probably not going to be acceptable in the long run. For long running code, I found about a 50% performance boost when I turned Option Strict ON and fixed all the issues it identified. That's too small to notice for most programs, but for a game server that could be HUGE.
As for the events, I think Atheist posted some example of using TCPListener for multiple clients. I thought he had put a thread in the CodeBank on the subject. You can look at his signature for a link to a thread on the subject, but that appears to have a link to this
http://www.vbforums.com/showpost.php...24&postcount=2
thread, which has a pretty good example, too. That might give you some ideas. It uses a perpetual loop, but the accept method is blocking, so the loop doesn't gobble up CPU time. It looks like you are using something similar, so you might not be using the CPU all that much either, though you also won't be able to end the thread by toggling your Boolean, since the loop will only run when a connection is requested. If there are no connections, the Boolean will never be tested.
Here's the original thread from Atheists signature. He put another client server TCP example at the end of it:
http://www.vbforums.com/showthread.php?t=502795
My usual boring signature: Nothing
 
-
Jan 14th, 2011, 12:58 AM
#10
Thread Starter
Junior Member
Re: Socket connection error
Alright, so I have successfully corrected all the compile errors caused by Option Strict being on and adapted Atheist code to mine.
Now I face another problem which is that everytime I try to connect to the listener, the error "Object reference not set to an instance of an object" gets trapped into the try-catch.
Any hint?
-
Jan 14th, 2011, 01:21 AM
#11
Re: Socket connection error
Post the details of the said exception. It should reveal more information on what is exactly wrong.
-
Jan 14th, 2011, 01:54 AM
#12
Banned
Re: Socket connection error
i want to learn this subject
what is Sockets.TcpClient ?
what is System.Net.Sockets.NetworkStream ?
what do they do, how do i use them ?
-
Jan 14th, 2011, 01:56 AM
#13
Re: Socket connection error
 Originally Posted by moti barski
i want to learn this subject
what is Sockets.TcpClient ?
what is System.Net.Sockets.NetworkStream ?
what do they do, how do i use them ?
Don't hi-jack someone's thread. Make a new thread instead, and you'll have to elaborate on what you want to do with them.
-
Jan 14th, 2011, 07:52 AM
#14
Thread Starter
Junior Member
Re: Socket connection error
System.NullReferenceException was unhandled
Message="Object reference not set to an instance of an object."
Source="WindowsApplication2"
StackTrace:
in WindowsApplication1.Form1.Listen(Object index) in C:\Users\username\Desktop\Visual Basic\Visual Basic 2008\Game\WindowsApplication2\Form1.vb:line 114
in System.Threading.ThreadHelper.ThreadStart_Context(Object state)
in System.Threading.ExecutionContext.runTryCode(Object userData)
in System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
in System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
in System.Threading.ThreadHelper.ThreadStart(Object obj)
InnerException:
-
Jan 14th, 2011, 09:03 AM
#15
Re: Socket connection error
We'd have to see the new version of the code, especially the line that throws the exception. If you don't know what line that is because it just shows up in the exception handler, you can change the exception behavior to break when the exception is raised. That can be found under Debug|Exceptions.
In general, that particular message always has the same general solution. The first step is to find the line that raises the exception, then examine every object in that line. One of the objects, which might be the return from a method, is Nothing, so when you look at each one, you will find one that is Nothing, which will greatly aid your search for the problem.
My usual boring signature: Nothing
 
-
Jan 14th, 2011, 01:49 PM
#16
Thread Starter
Junior Member
Re: Socket connection error
Code:
Private Sub Listen(ByVal index As Object)
Do
'Try
'tcp_client(CInt(index)) = New System.Net.Sockets.TcpClient
tcp_client(CInt(index)) = tcp_listener(CInt(index)).AcceptTcpClient 'line that throws exception
'Catch ex As Exception
'MsgBox(ex.Message)
'End Try
Loop
End Sub
-
Jan 14th, 2011, 03:37 PM
#17
Thread Starter
Junior Member
Re: Socket connection error
Nevermind. I just had to add "ReDim tcp_client(max_players)" to my code. Now it works. 
Thanks a lot to all of you.
-
Jan 14th, 2011, 03:44 PM
#18
Re: Socket connection error
Please mark your thread as Resolved in the "Thread Tools" menu at the top right hand side of the screen.
-
Jan 14th, 2011, 03:47 PM
#19
Thread Starter
Junior Member
Re: [RESOLVED] Socket connection error
-
Jan 14th, 2011, 04:10 PM
#20
Member
Re: [RESOLVED] Socket connection error
great job, seems like u got ur help already.. If u need something professional like this. look at this its 100% amazing: http://www.vbforums.com/showthread.p...highlight=chat
-
Jan 14th, 2011, 05:09 PM
#21
Re: [RESOLVED] Socket connection error
One thing I would add is that you ought to have a look at the List (of T). This was a new object added in VS2005. If you are using arrays that need to be re-sized, the List is a vast improvement over the array. You can add or insert items, remove items, and so on, and the sizing of the list is handled efficiently for you without any extra effort. In your case you would be using a List(of TCPListener). Rather than sizing the thing, you would add new ones with:
.Add(New TCPListener)
or whatever you chose. This is also strongly typed, such that if you make a List (of Integer), then it can ONLY hold integers. If you make a List(of TCPListener) then it can ONLY hold TCPListener...or anything derived from TCPListener.
Very convenient, and has largely replaced arrays except for those cases where the array is of a fixed size that, once set, doesn't change.
My usual boring signature: Nothing
 
-
Jan 14th, 2011, 08:17 PM
#22
Thread Starter
Junior Member
Re: [RESOLVED] Socket connection error
Okay. First it appeared to work (I am able to connect to the sever) when I was improving my game, but when I tried to connect with another client it didn't connect. 
Here's my server code:
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If Not serving Then
Dim slots As Integer = CInt(Replace(TextBox1.Text, " ", Nothing))
If IsNumeric(slots) Then
If slots > 0 And slots < 11 Then
serving = True
Button1.Text = "Serving..."
Dim port As Integer = 21760
max_players = slots
ReDim tcp_listener(max_players)
ReDim tcp_client(max_players)
For a As Integer = 0 To max_players - 1
tcp_listener(a) = New System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, port)
tcp_listener(a).Start()
port = port + 1
Timer1.Start()
Timer5.Start()
Next
Dim thread As New System.Threading.Thread(AddressOf Listen)
thread.IsBackground = True
thread.Start()
Else
MsgBox("The slots number must be between 1 and 10.", MsgBoxStyle.Critical, "Error")
End If
Else
MsgBox("The slots number must be a number.", MsgBoxStyle.Critical, "Error")
End If
End If
End Sub
Private Sub Listen(ByVal index As Object)
Do
Try
tcp_client(CInt(index)) = tcp_listener(CInt(index)).AcceptTcpClient
tcp_listener(CInt(index)).Stop()
Dim data As String = "connection1|"
Dim stream_writer As New System.IO.StreamWriter(tcp_client(CInt(index)).GetStream)
stream_writer.Write(data)
stream_writer.Flush()
tcp_client(CInt(index)).GetStream.BeginRead(readBuffer, 0, 255, AddressOf Data_Arrival, Nothing)
Exit Sub
Catch ex As Exception
MsgBox(ex.Message)
End Try
Loop
End Sub
Client code:
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If Not connecting Then
connecting = True
Button1.Text = "Connecting..."
TextBox1.ReadOnly = True
username = TextBox1.Text
Dim thread As New System.Threading.Thread(AddressOf Connect)
thread.IsBackground = True
thread.Start(current_port)
Timer4.Start()
End If
End Sub
Private Sub Connect(ByVal port As Object)
Try
current_port = CInt(port)
tcp_client = New System.Net.Sockets.TcpClient("ip.ip.ip.ip", CInt(port))
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
If you need any further info just ask.
-
Jan 14th, 2011, 09:23 PM
#23
Re: [RESOLVED] Socket connection error
Were any errors thrown? What happened exactly? Were there any messages displayed? The only thing that I could see being wrong is somewhere in the server code.
-
Jan 14th, 2011, 10:29 PM
#24
Thread Starter
Junior Member
Re: [RESOLVED] Socket connection error
I get no errors. It just doesn't connect.
-
Jan 15th, 2011, 04:02 PM
#25
Thread Starter
Junior Member
Re: [RESOLVED] Socket connection error
Is it to ask too much asking if someone could actually try the code?
-
Jan 18th, 2011, 06:26 PM
#26
Thread Starter
Junior Member
Re: Socket connection error
Ok. Nevermind. I fixed it myself. See you never.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|