Trying to connect to second Laptop. - Page 3-VBForums
Page 3 of 3 FirstFirst 123
Results 81 to 95 of 95

Thread: Trying to connect to second Laptop.

  1. #81

    Thread Starter
    Frenzied Member Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Near Barnsley South Yorkshire, England.
    Posts
    1,355

    Re: Trying to connect to second Laptop.

    Quote Originally Posted by PlausiblyDamp View Post
    You might need to either declare it as an IpEndPoint or if it is being returned from a method try casting it to an IpEndPoint, EndPoint is a base class which doesn't have an Address property.

    https://msdn.microsoft.com/en-us/lib...v=vs.110).aspx
    Thanks PlausiblyDamp,

    That's pointed me in the right direction, it's a bit of a roundabout route but it gets there.
    Code:
        Private Sub SvrGot(ByVal token As IAsyncResult)
            Dim ipa As String
            Dim Ears As TcpListener = CType(token.AsyncState, TcpListener)
    
            palPC = Ears.EndAcceptTcpClient(S_Token)
            ipa = palPC.Client.RemoteEndPoint.ToString
            ipa = ipa.Substring(0, InStr(ipa, ":") - 1)
            Pal = IPAddress.Parse(ipa)
            palName = System.Net.Dns.GetHostEntry(ipa).HostName.ToString
            UpDate_T(palName & " connected !")
            S_Token = Nothing
    
            ' Since we have a client connection, there's no good reason to keep listening!
            Ears.Stop()
    
            ' Start listening for messages from the client.
            ListenToClient(palPC)
        End Sub
    All that just to get the name of the 'remote' computer !
    Sadly it's not a vital part of my project, but it highlights one of my problems... I like to get all the bells and whistles working as I go along instead of getting the bare bones working first.


    Poppa.
    Along with the sunshine there has to be a little rain sometime.

  2. #82

    Thread Starter
    Frenzied Member Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Near Barnsley South Yorkshire, England.
    Posts
    1,355

    Question to Sitten Spynne

    Hi Sitten Spynne, I've just found a problem, or a question at least with regard to your attached code for Async Chat in post #54 on the 1st September.
    Code:
        Private Sub WhenClientConnectsToServer(ByVal state As Object)
            ' Note that sometimes asynchronous things don't return a result. You still have to call the 'End' method!
            _remoteClient.EndConnect(_clientConnectToken)
            _clientConnectToken = Nothing
            SetStatus("Connected!")
    
            ListenToClient(_remoteClient)
        End Sub
    I don't understand the 'ByVal state As Object', yes I understand what it means, but what does it do?

    'state' doesn't seem to be used anywhere else in the subroutine. Maybe the 'Nothing' in the subroutine...
    Code:
        Private Sub ConnectToServer(ByVal ipInput As String)
            Dim remoteAddress = IPAddress.Parse(ipInput)
            Dim port = 3000
            _remoteClient = New TcpClient()
    
            _clientConnectToken = _remoteClient.BeginConnect(remoteAddress, port, AddressOf WhenClientConnectsToServer, Nothing)
            SetStatus("Connecting...")
        End Sub
    ... is what's being passed? And maybe the '(ByVal state As Object)' is a requirement of that form of call to a subroutine?

    I'm trying to use a version of this subroutine in a test project and have a problem in this area and wonder if this is where my problem lays.


    Poppa.
    Along with the sunshine there has to be a little rain sometime.

  3. #83
    Fanatic Member PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Newport, UK
    Posts
    520

    Re: Trying to connect to second Laptop.

    Quote Originally Posted by Poppa Mintin View Post
    Thanks PlausiblyDamp,

    That's pointed me in the right direction, it's a bit of a roundabout route but it gets there.
    Code:
        Private Sub SvrGot(ByVal token As IAsyncResult)
            Dim ipa As String
            Dim Ears As TcpListener = CType(token.AsyncState, TcpListener)
    
            palPC = Ears.EndAcceptTcpClient(S_Token)
            ipa = palPC.Client.RemoteEndPoint.ToString
            ipa = ipa.Substring(0, InStr(ipa, ":") - 1)
            Pal = IPAddress.Parse(ipa)
            palName = System.Net.Dns.GetHostEntry(ipa).HostName.ToString
            UpDate_T(palName & " connected !")
            S_Token = Nothing
    
            ' Since we have a client connection, there's no good reason to keep listening!
            Ears.Stop()
    
            ' Start listening for messages from the client.
            ListenToClient(palPC)
        End Sub
    All that just to get the name of the 'remote' computer !
    Sadly it's not a vital part of my project, but it highlights one of my problems... I like to get all the bells and whistles working as I go along instead of getting the bare bones working first.


    Poppa.
    Did you try casting the palPC to an IPEndPoint rather than going via string conversion / parsing?

  4. #84

    Thread Starter
    Frenzied Member Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Near Barnsley South Yorkshire, England.
    Posts
    1,355

    Re: Question to Sitten Spynne

    Quote Originally Posted by Poppa Mintin View Post
    Hi Sitten Spynne, I've just found a problem, or a question at least with regard to your attached code for Async Chat in post #54 on the 1st September.
    Ok, I've sorted that out... My surmise was correct it seems.

    My problem was that although the two computers were connecting, my code said they weren't.
    It also turns out that my Win.7 lappy isn't as fast as my i7 Win.10 lappy! So I have to build-in a short delay.


    Poppa.
    Along with the sunshine there has to be a little rain sometime.

  5. #85
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    3,838

    Re: Trying to connect to second Laptop.

    Post #54 is one of your own posts. I'm not quite sure when that code was featured, but there's "no reason" and "a good reason" why that parameter was there. It's a bit of a mistake on my part, but not a very serious one.

    If you read the documentation for BeginConnect() (and most async methods using this pattern), you'll see that callback parameter is an AsyncCallback delegate type. That is a Sub that takes an IAsyncResult parameter.

    Remember that the pattern dictates after you call BeginSomething(), you must call EndSomething(). Usually, you pass along a "state" object which has a reference to "the thing I called BeginSomething() on". That object is part of the IAsyncResult, and that IAsyncResult is passed as a parameter to the callback so it can properly call EndSomething().

    But in this case, I already had a more convenient reference to "the thing that called BeginSomething()", so I used that and ignored the parameter. It was Object because this was a very early bit of code, and I couldn't remember that the parameter to the callback was IAsyncResult. Since IAsyncResult can be cast to Object, VB didn't complain that it didn't exactly match. Don't ask me to explain the delegate conversion rules, I've never understood them.

    But since that parameter is part of AsyncCallback's required signature, I have to provide it even if I don't use it.

    Similar things happen with the Thread class, it wants a delegate that is a Sub that takes 1 Object parameter for state. Even if you don't use it, you have to have that parameter.

    As usual: "I had to build in a short delay" means nothing to me. When you speak in paragraphs I can't understand you. When you show me code, I can comprehend.

    I say this because "when something is broken", we have to write "bad" code that won't work on other machines to make it work. That doesn't mean "the bad code is sometimes good". That means "I need to fix the problem with my network configuration so the code that works everywhere else can work on my machine." So I need to see what you did to "fix" it to maybe gain some insight into what went wrong.

    Otherwise every bit of code I write will be broken on your machine, and you'll have to solve the, 'How do I tweak it to make it work?' game. That is a tiring game of 20 questions where almost none of my experience helps me help you. I don't want to play that game and don't want to write more code examples until the code that works on 99% of computers also works on yours.
    Last edited by Sitten Spynne; Oct 16th, 2017 at 09:24 AM.
    Nothing I post is production-ready. It is provided as-is, use it at your own risk.

  6. #86

    Thread Starter
    Frenzied Member Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Near Barnsley South Yorkshire, England.
    Posts
    1,355

    Re: Trying to connect to second Laptop.

    Quote Originally Posted by Sitten Spynne View Post
    Post #54 is one of your own posts.
    Ah... Yeah, I just checked, I don't know how that happened... Ought to've been post# 57.


    Poppa.
    Along with the sunshine there has to be a little rain sometime.

  7. #87

    Thread Starter
    Frenzied Member Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Near Barnsley South Yorkshire, England.
    Posts
    1,355

    Re: Trying to connect to second Laptop.

    Quote Originally Posted by Sitten Spynne View Post
    As usual: "I had to build in a short delay" means nothing to me. When you speak in paragraphs I can't understand you. When you show me code, I can comprehend.

    I say this because "when something is broken", we have to write "bad" code that won't work on other machines to make it work. That doesn't mean "the bad code is sometimes good". That means "I need to fix the problem with my network configuration so the code that works everywhere else can work on my machine." So I need to see what you did to "fix" it to maybe gain some insight into what went wrong.

    Otherwise every bit of code I write will be broken on your machine, and you'll have to solve the, 'How do I tweak it to make it work?' game. That is a tiring game of 20 questions where almost none of my experience helps me help you. I don't want to play that game and don't want to write more code examples until the code that works on 99% of computers also works on yours.
    I thought I'd fixed it, so code wasn't required. But you're right it's likely to be a 'Fix' rather than a solution, so first the code which didn't work, or rather the code which stopped working.

    I'm trying to avoid having to start with the decision 'Server or Client' so my project starts in Server mode but looks to see if any computers are active on the LAN (Same router). If one or more is found there's an option to choose which computer to try to connect to. Here there's only my missus and I so there's only ever one other computer, but doing it that way means that if we know the other has the game (to be) open either of us can start it.

    Currently Form1 contains just:
    1: ListBox. to display active computers. (excluding the host machine) thus '192.168.0.3. iKi_Lappy' (Address Space Name)
    1: TextBox. to display status.
    3: Buttons.
    'Exit'.
    'Start' (Look for other computers).
    'Test' Will be used to try communications.

    This is the previous code to connect to the other computer:
    Code:
        Private Sub Get_Clnt()
            palPC = New TcpClient()
            C_Token = palPC.BeginConnect(Pal, Port, AddressOf Got_Clnt, Nothing)
    
        End Sub 'Connect to Client.
        
        Private Sub Got_Clnt(ByVal state As Object)
            Try
                palPC.EndConnect(C_Token)
                C_Token = Nothing
                TextBox1.Text = vbCrLf & "Connected to " & palName
            Catch ex As Exception
                Dim txt As String = vbCrLf & "Sorry... Not connected !" & vbCrLf & vbCrLf
                UpDate_T(txt & "Listening for Friend")
                StartServer()
            End Try
    
        End Sub ' Connected to Client... Or not.
    This used to work almost immediately if the Win.7 machine tried to connect, but got to be that if the Win.10 machine tried to connect it didn't, although it did in fact connect some five or so seconds later. I'm pretty sure it worked at first before I started trying to actually use it.

    This is how the code is now, I've added other parts so that you can see (what I hope is all) the relevant bits.
    Code:
        Private Sub Lbx1() Handles ListBox1.SelectedValueChanged
            '       I am now the Client !
            Dim LbxS As String = CType(ListBox1.SelectedItem, String)
            Dim Splt() As String = Split(LbxS)
            Dim Adr As String = Splt(0).Substring(0, Splt(0).Length - 1)
            SvrStop()
            Pal = IPAddress.Parse(Adr)
            palName = Splt(3)
            TextBox1.Text = vbCrLf & "Trying to connect to " & palName
            TextBox1.Refresh()
            Get_Clnt()  '   Connect to Server
            GameStart()
    
        End Sub ' Make me the Client!
    
        Private Sub Get_Clnt()
            palPC = New TcpClient()
            C_Token = palPC.BeginConnect(Pal, Port, AddressOf Got_Clnt, Nothing)
    
        End Sub ' Client: Connect to Server.
    
        Private Sub Got_Clnt(ByVal state As Object)
            Try
                palPC.EndConnect(C_Token)
                C_Token = Nothing
            Catch ex As Exception
            End Try
    
        End Sub ' Client: Connected to Server... Or not.
    
        Private Sub SvrStop()
            Try
                S_Ears.Stop()
            Catch ex As Exception
            End Try
    
        End Sub ' Server: Stop listening.
    
        Private Sub GameStart()
            System.Threading.Thread.Sleep(6000) ' Allow time for 'Pal' to connect.
            If palPC.Connected Then
                TextBox1.Text = vbCrLf & "Connected to " & palName
                ListBox1.Dispose()
                Button2.Visible = False
                Button3.Visible = True
            Else
                Dim txt As String = vbCrLf & "Sorry... Not connected !" & vbCrLf & vbCrLf
                UpDate_T(txt & "Listening for Friend")
                StartServer()
                Exit Sub
            End If
    
        End Sub ' Both connected.
    Poppa.
    Along with the sunshine there has to be a little rain sometime.

  8. #88
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    3,838

    Re: Trying to connect to second Laptop.

    Yes. This is definitely a case of "doing the wrong thing and fixing it with wrong code".

    The word "asynchronous" means the idea of two things happening at the same time, in parallel. When you call code that is asynchronous, you are saying, "Start doing this, but let me keep going. Call me when you are finished." Let me try to express it with analogy, then tie it back to the code you wrote.

    Suppose you need to do two things today. You need to buy some groceries, and you need to watch a movie with your wife. The movie you want to watch is at the Redbox machine at the grocery store. She hands you a grocery list and says, "Please go to the store for me." That's BeginShopping(). Now one of two things can happen. Let's look at the code.


    That paragraph looks like this:
    Code:
    Sub DoThings()
        you.Items.Add(groceryList)
        you.BeginShopping(AddressOf EndShopping)
    
        wife.DoSomething()
    
        wife.TakeMovie() ' CRASH: you aren't even in the house anymore.
        wife.WatchMovie()
    End Sub
    
    Sub EndShopping()
        you.GiveMovieToWife()
        you.WatchMovie()
    End Sub
    Maybe the "DoSomething()" your wife does takes a long time. If it does, you might get back from shopping before she finishes. So by the time she does "TakeMovie()", you're back with the movie and it all works. This is what's happening on one of your PCs.

    But what if the "DoSomething()" is really quick, and she tries to TakeMovie() before you get back? You aren't there, so there's no movie, so the program crashes and the universe ends. Oops.

    So when you write asynchronous code, you have to make sure if something assumes the code is finished, it doesn't happen until AFTER the thing finishes:

    Code:
    Sub DoThings()
        you.Items.Add(groceryList)
        you.BeginShopping(AddressOf EndShopping)
    
        wife.DoSomething()
    End Sub
    
    Sub EndShopping()
        you.GiveMovie()
        wife.TakeMovie()
        you.WatchMovie()
        wife.WatchMovie()
    End Sub
    Back to your code.

    When you call BeginConnect(), you are telling the computer: "Go try to make a connection on another thread. Don't call me back until there is an error or it has finished." The method "Got_C1nt()" will be called from that other thread when it finishes.

    But your code barrels onwards and calls GameStart(), which assumes you've already finished making the connection. On one PC, the connection finishes fast enough that this is true by accident. On the other PC, it takes a little while longer, and GameStart() rightfully complains the connection isn't ready yet. When you add a Thread.Sleep(), you cause GameStart() to wait long enough for the connection to happen.

    But that defeats the purpose of using asynchronous code at all.. The whole point is "I don't want to freeze the UI thread", and nothing freezes the UI thread quite like Thread.Sleep().

    This is what your code should look like:
    Code:
    Private Sub ListBox1_SelectedValueChanged() Handles ...
        ' blah blah parsing code
        TextBox1.Text = vbCrLf & "Trying to connect to " & palName
        Get_C1nt()
    End Sub
    
    Private Sub Get_C1nt()
        palPC = New TcpClient()
        C_Token = palPC.BeginConnect(...)
    End Sub
    
    Private Sub Got_C1nt()
        Try
            palPC.EndConnect(C_Token)
            C_Token = Nothing
    
            Me.Invoke(AddressOf GameStart)
        Catch ex As Exception
            MessageBox.Show("Don't ever let me see an empty Catch again.")
        End Catch
    End Sub
    
    Private Sub GameStart()
        ...
    All I did was move the GameStart() call from the initial event handler to the thing that is called after the connection completes. I did add the call to Invoke(), because I know that will be on a worker thread and GameStart() wants to be on the UI thread.

    Remember: calling BeginConnect() is not "Make the connection and wait for it to finish." It is "Make the connection and call me back when you finish." IIRC the whole reason we started down this rabbit hole was, "Why does the UI freeze?" Any time you say, "Wait", it will freeze. Getting around UI freezes involves finding ways to say, "Do this and call me back when you finish." It's the difference between "going to the grocery store" and "getting the groceries delivered".
    Nothing I post is production-ready. It is provided as-is, use it at your own risk.

  9. #89

    Thread Starter
    Frenzied Member Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Near Barnsley South Yorkshire, England.
    Posts
    1,355

    Re: Trying to connect to second Laptop.

    OK, I take that point, I thought Get_Clnt() would only complete after Got_Clnt() completed. (Obviously didn't think hard enough).

    I've added a new button and now only startServer with that button so that I could remove the 'StopServer' subroutine and just stop the server where you stop it in the original code, because that subroutine wasn't stopping the server... I hope this is a temporary measure.

    In both machines I have VS2017 fully up-to-date, what I do is:
    Modify the project, (usually on the Win.10 machine), run it to build the .exe file, then copy that file onto a 'USB memory stick'. Then, using the 'stick' I test the project between the two computers. If that fails to work correctly I copy the whole project folder onto the other machine, build it and run it in Debug from there... Oughtn't to make a difference but I do it 'just in case'. I don't recall a time when it did make a difference.

    So, I'm back to my original problem, back where I was quite a long time ago. Which, as has been suggested several times before, may be a function of a firewall or anti-virus application.

    I open the project on the Win.10 machine, leave it in Server mode... Listening. Then open the project on the Win.7 machine and try to connect and it connects seemingly instantly. Then exit applications on both machines, reopen both, this time I leave the Win.7 listening and try to connect with the Win.10 machine which fails. From what you say with regard to 'StartGame' barreling on it may well be that there never was a connection in that direction, I was just fooled into believing there was. I haven't got around to trying to actually send data between the two machines yet, that's next once I've got the connection working both ways.

    I've tried looking at the firewall (AVG Free) on the Win.7 machine (which I think is the logical machine to look at) I've tried to set my project as an exclusion, but I'm not at all sure I've done that correctly... The 'Help' isn't very helpful. It talks about webpage URLs, file paths, files and folders but I don't see how to enter another computer asking for a connection, so I've just entered the file name. I've also entered the five addresses '192.168.0.' plus 2 to 6. (Our computers are currently '192.168.0.2' and '192.168.0.3' ).


    Poppa.
    Along with the sunshine there has to be a little rain sometime.

  10. #90
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    3,838

    Re: Trying to connect to second Laptop.

    Well, we've been in this spot before.

    Early in the thread, there were very simple programs, and part of their purpose was "run these to make sure network connectivity works". I vaguely remember telling the story that I keep them around because network code can be finicky, and it's useful to make sure there's not a real hardware issue before debugging. Go back and find one of those. That's more reliable than running some code that we're not sure works.
    Nothing I post is production-ready. It is provided as-is, use it at your own risk.

  11. #91

    Thread Starter
    Frenzied Member Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Near Barnsley South Yorkshire, England.
    Posts
    1,355

    Re: Trying to connect to second Laptop.

    Quote Originally Posted by Sitten Spynne View Post
    Well, we've been in this spot before.
    Early in the thread, there were very simple programs, and part of their purpose was "run these to make sure network connectivity works".

    Go back and find one of those. That's more reliable than running some code that we're not sure works.
    Hi,

    I did that two days ago, but I did it again this evening to be sure I remembered the test and the results correctly.
    I've been using the Form1.vb file from the zip file which you attached to post# 57, (correct number this time) Async Chat 2017.zip, as the basis for 'Just Connect' which, as the name suggests it was just supposed to check the connection...
    ...but it's grown a bit !

    The Async Chat 2017 project is still on both computers. I opened it on both, selected the Win.7 machine as the Server and clicked start. On the Win.10 machine I entered the address of the Win.7 machine (This is the direction which doesn't work with my code) selected Client, clicked Start and the Form1 heading on both said 'Chatting'. I sent a message both ways.

    Then I closed both app's and did the same again but swapped the Server and Client, again both worked properly. Which seems to suggest that the problem isn't either machine don't you think ?


    Poppa.
    Last edited by Poppa Mintin; Oct 17th, 2017 at 07:19 PM. Reason: Typo.
    Along with the sunshine there has to be a little rain sometime.

  12. #92
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    3,838

    Re: Trying to connect to second Laptop.

    Yep. It sounds like the problem is in the modified code. You keep describing it and saying what you did to it, but the only real way to describe code is to post it. The devil's in the details.
    Nothing I post is production-ready. It is provided as-is, use it at your own risk.

  13. #93

    Thread Starter
    Frenzied Member Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Near Barnsley South Yorkshire, England.
    Posts
    1,355

    Re: Trying to connect to second Laptop.

    Quote Originally Posted by Sitten Spynne View Post
    Yep. It sounds like the problem is in the modified code. You keep describing it and saying what you did to it, but the only real way to describe code is to post it. The devil's in the details.
    The Form1 is as previously described, Button3 starts invisible under ListBox1.

    Code:
    Imports System.IO
    Imports System.Net
    Imports System.Net.Sockets
    
    Public Class Form1
        Private C_Token As IAsyncResult
        Private S_Token As IAsyncResult
        Public check, MyIDnum As Int32
        Private Port As Int32 = 3000
        Public myID, Pal As IPAddress
        Public EarsEP As IPEndPoint
        Public HostName, MyName, palName As String
        Public palPC As TcpClient
        Public S_Ears As TcpListener
    
        Private Sub Form1_Load() Handles MyBase.Load
            TextBox1.Location = New Point(1, ListBox1.Height + 2)
            TextBox1.Height = Button1.Location.Y - TextBox1.Location.Y - 2
            Button1.Text = "Exit"
            Button2.Text = "Seek"
            Button3.Text = "Test"
            Button4.Text = "Wait"
            Me.Show()
            Me.TopMost = True
            WhoAmI()
            TextBox1.Text = "Seek:-    For Others" & vbCrLf & "Wait:-    For Friend"
            Me.Refresh()
        End Sub
    
    
    
        Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
            '	Dont forget to dispose everything in here.
        End Sub
    
        Private Sub Button1_Click() Handles Button1.Click
            CloseMeDown()
        End Sub ' Exit.
    
        Private Sub Button2_Click() Handles Button2.Click
            TextBox1.Text = vbCrLf & "Please wait"
            TextBox1.Refresh()
            Dat = 0
            Button1.Focus()
            Button2.Visible = False
            Button4.Visible = False
            check = CInt(Val(TextBox1.Text))
            If check < 6 Then check = 6
            Seek()
        End Sub ' Start.   Temp !
    
        Private Sub Button3_Click() Handles Button3.Click 
            '	Test data swap in here.
            Me.Close()
        End Sub ' Message. 
    
        Private Sub Button4_Click() Handles Button4.Click
            Button2.Visible = False
            Button4.Visible = False
            TextBox1.Text = vbCrLf & "Listening for Friend"
            StartServer()
        End Sub
    
        Private Sub CloseMeDown()
            If Me.InvokeRequired Then
                Me.Invoke(Sub() CloseMeDown())
            Else
                UpDate_T("Closing !")
                Me.Close()
            End If
        End Sub
    
        Private Sub GameStart()
            TextBox1.Text = vbCrLf & "Connected to " & palName
            '   Won't need Listbox any further.
            ListBox1.Dispose()
            Button2.Visible = False
            Button3.Visible = True ' Enable comm's test
            Button4.Visible = False
        End Sub
    
        Private Sub Get_Clnt()
            palPC = New TcpClient()
            C_Token = palPC.BeginConnect(Pal, Port, AddressOf Got_Clnt, Nothing)
        End Sub ' Client: Connect to Server.
    
        Private Sub Got_Clnt(ByVal state As Object)
            Try
                palPC.EndConnect(C_Token)
                C_Token = Nothing
                If palPC.Connected Then GameStart()
            Catch ex As Exception
                Dim txt As String = vbCrLf & "Sorry... Not connected !" & vbCrLf & vbCrLf
                UpDate_T(txt & "Listening for Friend")
                StartServer()
            End Try
        End Sub ' Client: Connected to Server... Or not.
    
        Private Sub Lbx1() Handles ListBox1.SelectedValueChanged
            '       I am now the Client !
            Dim LbxS As String = CType(ListBox1.SelectedItem, String)
            Dim Splt() As String = Split(LbxS)
            Dim Adr As String = Splt(0).Substring(0, Splt(0).Length - 1)
            Pal = IPAddress.Parse(Adr)
            palName = Splt(3)
            TextBox1.Text = vbCrLf & "Trying to connect to " & palName
            TextBox1.Refresh()
            Get_Clnt()  '   Connect to Server
        End Sub ' Make me the Client!
    
        Private Sub Seek()
            Dim Echo, ipa, txt As String, pc As Int32, Yes As Boolean
            ListBox1.Items.Clear()
            For i = 2 To check
                pc = CInt(i * 100 / check)
                ipa = "192.168.0." & i.ToString
                Yes = My.Computer.Network.Ping(ipa)
                If i <> MyIDnum And Yes Then
                    Try
                        Echo = System.Net.Dns.GetHostEntry(ipa).HostName.ToString
                        ListBox1.Items.Add(ipa & ".   " & Echo)
                    Catch ex As Exception
                        UpDate_T(ex.ToString)
                    End Try
                End If
                TextBox1.Text = vbCrLf & "Please wait" & vbCrLf & vbCrLf
                TextBox1.Text += "Seeking connections...  " & pc.ToString & "%"
                Me.Refresh()
            Next
            If ListBox1.Items.Count > 0 Then
                TextBox1.Text = "Please select"
            Else
                txt = "Sorry..." & vbCrLf & "No other computers found."
                txt += vbCrLf & vbCrLf & "Listen for a Player ?"
                TextBox1.Text = txt
                Button2.Visible = True
                Button4.Visible = True
            End If
        End Sub ' Find other computers.
    
        Private Sub StartServer()
            '       I am Server !
            Try
                EarsEP = New IPEndPoint(IPAddress.Any, 3000)
                Dim S_Ears As New TcpListener(EarsEP)
                S_Ears.Start()
                S_Token = S_Ears.BeginAcceptTcpClient(AddressOf SvrGot, S_Ears)
            Catch ex As Exception
                UpDate_T("StartServer" & vbCrLf & ex.ToString)
            End Try
        End Sub ' Start listening.
    
        Private Sub SvrGot(ByVal token As IAsyncResult)
            Dim ipa As String
            S_Ears = CType(token.AsyncState, TcpListener)
            palPC = S_Ears.EndAcceptTcpClient(S_Token)
            ipa = palPC.Client.RemoteEndPoint.ToString
            ipa = ipa.Substring(0, InStr(ipa, ":") - 1)
            Pal = IPAddress.Parse(ipa)
            palName = System.Net.Dns.GetHostEntry(ipa).HostName.ToString
            UpDate_T(palName & " connected !")
            S_Token = Nothing
            ' Since we have a client connection, there's no good reason to keep listening!
            S_Ears.Stop()
            If Me.InvokeRequired Then
                Me.Invoke(Sub() GameStart())
            Else
                GameStart()
            End If
            '' Start listening for messages from the client.
            'ListenToClient(palPC)
        End Sub ' Connected to Server... Or not.
    
        Private Sub UpDate_T(ByVal txt As String)
            If Me.InvokeRequired Then
                Me.Invoke(Sub() UpDate_T(txt))
            Else
                TextBox1.Text = txt
                TextBox1.Refresh()
            End If
        End Sub
    
        Private Sub WhoAmI()
            Dim ad As New List(Of String)
            ad.Clear()
            HostName = Dns.GetHostName()
            Dim host As IPHostEntry = Dns.GetHostEntry(HostName)
            Dim ip As IPAddress() = host.AddressList
            Dim i As Int32
            For i = 0 To ip.Length - 1
                myID = ip(i)
            Next
            Dim ID As String = myID.ToString
            Dim spt() As String = Split(ID, ".")
            MyIDnum = CInt(Val(spt(3)))
        End Sub ' Get my name and address.
    
    End Class
    I don't like 'flooding' posts so usually I only post what I think is relevant.
    Note: Explaining 'check', temporarily set at 6 but can be set to the lowest number of addresses likely to be found on local LAN, can be adjusted without altering any code by typing in a new number before clicking 'Start'.

    Poppa.
    Along with the sunshine there has to be a little rain sometime.

  14. #94

    Thread Starter
    Frenzied Member Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Near Barnsley South Yorkshire, England.
    Posts
    1,355

    Re: Trying to connect to second Laptop.

    Hmmm....

    I don't know what (or if) I've done.
    Code is working now !
    As far as it goes... Can start working on data transfer now.


    Poppa.
    Along with the sunshine there has to be a little rain sometime.

  15. #95
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    3,838

    Re: Trying to connect to second Laptop.

    Quote Originally Posted by Poppa Mintin View Post
    Hmmm....

    I don't know what (or if) I've done.
    Code is working now !
    If you had posted the code here, we could tell you what you did. Now the opportunity to learn something has been lost.

    Post your code. It's not too much, and if I don't think I need to see it it's easier to skip the code blocks than it is to skim a paragraph.

    My psychic guess: your execute a ton of code per connection to, in a roundabout way, get a host entry for an IP. If anything goes wrong in that process, an exception is thrown, and GameStart() won't get called. (It's fairly likely, because there's not always a host entry for a given IP.) Because that exception is on a worker thread, the thread quits. Because that was a worker thread and not the main thread, the program doesn't crash. My advice:

    If the method is named SvrGot, it should Got the Svr, not "accept the client, try to get a hostname and fail completely if I can't, then start the game". I don't know what a Svr is or what it means to Got it, so this is how I'd write that snippet of code:
    Code:
        Private Sub WhenTcpClientConnects(ar As IAsyncResult)
            Dim listener = CType(ar.AsyncState, TcpListener)
            _remoteClient = listener.EndAcceptTcpClient(ar)
    
            ReportConnection()
    
            GameStart()
        End Sub
    
        Private Sub ReportConnection()
            Dim info = GetConnectionInfo()
            If info.WeirdInfo IsNot Nothing Then
                Debug.WriteLine("Got a weird connection: {0}", info.WeirdInfo)
            End If
    
            If info.Hostname IsNot Nothing Then
                Debug.WriteLine("Got a connection from {0} ({1})", info.Hostname, info.IPAddress)
            ElseIf info.IPAddress IsNot Nothing Then
                Debug.WriteLine("Got a connection from {0}.", info.IPAddress)
            End If
        End Sub
    
        Private Function GetConnectionInfo() As ConnectionInfo
            ' This means it was called at a time when there isn't a connection.
            If _remoteClient Is Nothing Then
                Return New ConnectionInfo()
            End If
    
            Dim result As New ConnectionInfo
            Dim remoteEndPoint = _remoteClient.Client.RemoteEndPoint
            Dim usefulEndPoint = TryCast(remoteEndPoint, IPEndPoint)
            If usefulEndPoint Is Nothing Then
                ' Not sure how you get a "not IP endpoint" but here we are.
                result.WeirdInfo = remoteEndPoint.ToString()
            End If
    
            result.IPAddress = result.IPAddress
    
            Try
                Dim hostEntry = Dns.GetHostEntry(result.IPAddress)
                result.Hostname = hostEntry.ToString()
            Catch ex As Exception
                ' Whoops, couldn't get the hostname.
                Debug.WriteLine("Failed to resolve a hostname.")
            End Try
    
            Return result
    
        End Function
    
        Private Class ConnectionInfo
            Public IPAddress As IPAddress
            Public Hostname As String
    
            Public WeirdInfo As String
        End Class
    Part of understanding what goes wrong in your code is adding exception handlers and debug output so it tells you when it fails. When you are working asynchronously, failures don't always crash the application. So it's even more important than it was before to be sure your program tells you when it's sick.

    That means writing more code. But compare the 5-10 minutes it took me to write that code to the amount of time you've spent debugging this program! Every line of code you write to catch errors and log or handle them is worth 15 minutes of debugging saved.
    Last edited by Sitten Spynne; Oct 18th, 2017 at 09:35 AM.
    Nothing I post is production-ready. It is provided as-is, use it at your own risk.

Page 3 of 3 FirstFirst 123

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.