Page 5 of 7 FirstFirst ... 234567 LastLast
Results 161 to 200 of 273

Thread: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

  1. #161
    Addicted Member
    Join Date
    Jan 2007
    Posts
    199

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    I even try this one but directcast always give me error...

    Code:
        Private Sub SendMessageToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles SendMessageToolStripMenuItem.Click
    
            Dim strMsg As String = InputBox("Enter your message to selected terminal", "Message")
    
            If strMsg = String.Empty Then
                Exit Sub
            Else
                For Each SelectedItems As ListViewItem In Me.lv_main.SelectedItems
                    hostsComboBox.Items.Clear()
                    hostsComboBox.Items.Add(SelectedItems.Tag & ":" & SelectedItems.SubItems(18).Text)
    
                    If hostsComboBox.SelectedItem Is Nothing Then
                        hostsComboBox.SelectedIndex = 0
                    End If
    
                    Dim host = DirectCast(Me.hostsComboBox.SelectedItem, HostInfo)
    
                    ' SEND MESSAGE TO ALL CLIENT SELECTED
                    Me.server.Send(host, strMsg)
                Next
            End If
        End Sub

  2. #162
    Addicted Member
    Join Date
    Jan 2007
    Posts
    199

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Hi jmcilhinney I need help I on this project, I have problem when client disconnected/ via power off or unplug cable my client get still connected on my status. I made a timer so when client disconnect it will auto connect. my problem is on me.client.dispose() once I dispose client me.client.connect() I have an error it says I need to unload all instance before connecting again.

  3. #163

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Quote Originally Posted by tokneneng View Post
    Hi jmcilhinney I need help I on this project, I have problem when client disconnected/ via power off or unplug cable my client get still connected on my status. I made a timer so when client disconnect it will auto connect. my problem is on me.client.dispose() once I dispose client me.client.connect() I have an error it says I need to unload all instance before connecting again.
    That's too vague a description I'm afraid.

  4. #164
    Addicted Member
    Join Date
    Jan 2007
    Posts
    199

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Sorry for that. I have your DLL on my project. When I properly close the server and the client I have no issue. However I came to an issue where in I tried to power off and unplug network cable to test the continuity of server and client communication this comes the problem. So what I did I created a timer on the client side which tick every secs to check for connection issue on the server when on the timer I have this:

    vb Code:
    1. Private Sub tmr_idle_Tick(sender As System.Object, e As System.EventArgs) Handles tmr_idle.Tick
    2.         If tsl_idle.Text = "Disconnected" Or tsl_idle.Text = "Connection was closed by the server." Then
    3.             'Me.Dispose()
    4.             Me.client.Connect()
    5.             tmr_idle.Enabled = False
    6.         Else
    7.             If tsl_idle.Text = "Connected" Then
    8.                 tmr_idle.Enabled = False
    9.                 Exit Sub
    10.             End If
    11.         End If
    12.     End Sub

    When server back on client does not connect again.

  5. #165

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Firstly, you should not be testing the Text of a TextBox to determine a state. If there are only two possible states then you should probably be using a Boolean. If there are multiple states then you should be using an enumeration.

    As for your issue, you've show us the code and told us that it doesn't do what it's supposed to. So, what does happen?

  6. #166
    Addicted Member
    Join Date
    Jan 2007
    Posts
    199

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Quote Originally Posted by jmcilhinney View Post
    Firstly, you should not be testing the Text of a TextBox to determine a state. If there are only two possible states then you should probably be using a Boolean. If there are multiple states then you should be using an enumeration.

    As for your issue, you've show us the code and told us that it doesn't do what it's supposed to. So, what does happen?
    Thanks for the clarification regarding the textbox... about the code client does not connect nothing happen timer just keep on running. On server side I put a break point on server_ConnectionAccepted to see if communicate with the server but it does not break. This happen when I shutdown the client and re run it again to check if client auto connect to the server.

  7. #167
    Addicted Member
    Join Date
    Jan 2007
    Posts
    199

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    hi jmcilhinney can you gave idea how to fix it? thanks

  8. #168

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    I haven't looked at this code for a long time. It would be my guess that the TcpClient involved has been disposed and therefore cannot connect. You should check whether that is the case and, if so, either don't let the TcpClient be disposed until you are genuinely finished with or else create a new one when needed.

  9. #169
    PowerPoster i00's Avatar
    Join Date
    Mar 2002
    Location
    1/2 way accross the galaxy.. and then some
    Posts
    2,388

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    mixed packets?

    I am trying to send a heap of packets so made the send and receive accept objects instead of a string (that gets serialized into a byte array of course)...

    Works fine for one or two images ... but if i go:

    vb Code:
    1. For Each item In FileIO.FileSystem.GetFiles("C:\TestImages",FileIO.SearchOption.SearchTopLevelOnly,"*.jpg")
    2.             Me.client.Send(New Bitmap(item))
    3.         Next

    It works for the first few then the packets get mixed up and it throws on the de-serialization ...

    Any ideas on how to fix this?

    Thanks
    Kris

  10. #170

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    @i00, I'm afraid I don't know.

  11. #171

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    I would make the byte array by hand; the easiest way I know of doing that is reading the image to a memorystream, then calling the .ToByteArray(); however, since you have the path of the file, just ReadAllBytes() into an array, and handle it on the other side. I've never had the problem with that sort of working.

    EDIT: I speak from experience on this; serialization is nice for storing data locally, but really gets wonky when transferring across a network.

  12. #172
    New Member
    Join Date
    Jul 2011
    Posts
    2

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Dear Friend,

    Your code is great, really great! Can you help me to fix a problem that happens to the client when the server window is in closed state?

    When the client's FailedtoConnect is raised, your code prompts with a dialog box to get connected. I removed the question and directly put "client.connect" method instead of asking the question. But, it doesn't get connected when the Server is back online.

    Can you please point out why?

    Thank and regards,
    creativedas

  13. #173
    New Member
    Join Date
    Aug 2012
    Posts
    3

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Hi, your code is excellent. I have one issue that i hope that you can solve. I am sending data that is variable in length and the textbox is adding it in chunks. I would like to concatenate it into a onle-line entry. y string is terminated with a 'z'. I have no real control on the client transmission (and Arduino with an ehernet shield) with the exception of adding a null or not after the string to send. Either way the data appears in the text box on various lines.

    I am sending:
    IFC01:2023-2023-2023-2023-2023-2023-2023-2023-951-952-953-953-954-954-954-955-287-286-286-286-259-259-260-261-233-233-234-234-235-235-235-236-z
    and getting varying amounts per line:
    Message (192.168.0.103:1025=>): I
    Message (192.168.0.103:1025=>): F
    Message (192.168.0.103:1025=>): C0
    Message (192.168.0.103:1025=>): 1
    Message (192.168.0.103:1025=>): :
    Message (192.168.0.103:1025=>): 1
    Message (192.168.0.103:1025=>): 0
    Message (192.168.0.103:1025=>): 2
    Message (192.168.0.103:1025=>): 3
    Message (192.168.0.103:1025=>): -
    Message (192.168.0.103:1025=>): 1
    Message (192.168.0.103:1025=>): 0
    Message (192.168.0.103:1025=>): 2
    Message (192.168.0.103:1025=>): 3
    Message (192.168.0.103:1025=>): -1
    Message (192.168.0.103:1025=>): 023
    Message (192.168.0.103:1025=>): -
    Message (192.168.0.103:1025=>): 1
    Message (192.168.0.103:1025=>): 0
    Message (192.168.0.103:1025=>): 2
    Message (192.168.0.103:1025=>): 3-
    Message (192.168.0.103:1025=>): 1023-1023-1023-961-880-881-883-884-8
    Message (192.168.0.103:1025=>): 8
    Message (192.168.0.103:1025=>): 5
    Message (192.168.0.103:1025=>): -885-88
    Message (192.168.0.103:1025=>): 7-
    Message (192.168.0.103:1025=>): 8
    Message (192.168.0.103:1025=>): 87-149-148-148-149-149-149
    Message (192.168.0.103:1025=>): -
    Message (192.168.0.103:1025=>): 1
    Message (192.168.0.103:1025=>): 48-147-12
    Message (192.168.0.103:1025=>): 4-122
    Message (192.168.0.103:1025=>): -
    Message (192.168.0.103:1025=>): 120
    Message (192.168.0.103:1025=>): -1
    Message (192.168.0.103:1025=>): 1
    Message (192.168.0.103:1025=>): 8-
    Message (192.168.0.103:1025=>): 116
    Message (192.168.0.103:1025=>): -
    Message (192.168.0.103:1025=>): 1
    Message (192.168.0.103:1025=>): 1
    Message (192.168.0.103:1025=>): 4-112-109-z

  14. #174
    New Member
    Join Date
    Aug 2012
    Posts
    3

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    By the way I know that the above 2 sections do not coincide as sent and received. I hav to cut and paste from 2 locations. I have 2 clients that I am working with at the same time and the Arduino has no cut and pastable regions.

  15. #175
    New Member
    Join Date
    Aug 2012
    Posts
    3

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Hi jmcilhinney,

    Actually, I figured it out. It only took me "a few hours". I found a piece of code for making delays with an input parameter of integer (for the seconds).

    I then ended up putting it in a new line, just after the Read subroutine (I'm talking about the MessageServer code). This 2 second delay is not bad for my purposes and gives the buffer for each client to fill up with the entire transmission from the client(s). I would have liked to have found a more "correct" way to handle this. Something that would check each transmission for the "z" and not send the message to the textbox until it found it. But, alas, I have spent too many hours finding a usable tcp server for my purposes.

    I still have to handle some exceptions like when clients disconnect without grace.

    My revisions:

    Private Sub Read(ByVal ar As IAsyncResult)
    Delay(2)
    ... The rest of this code is unchanged.
    End Sb

    Private Sub Delay(ByVal dblSecs As Double)
    Const OneSec As Double = 1.0# / (1440.0# * 60.0#)
    Dim dblWaitTil As Date
    Now.AddSeconds(OneSec)
    dblWaitTil = Now.AddSeconds(OneSec).AddSeconds(dblSecs)
    Do Until Now > dblWaitTil
    ' Allow windows messages to be processed
    Loop

    End Sub


    Anyway, I want to thank you for your code. By far the best that I have found.

  16. #176
    Junior Member
    Join Date
    Sep 2012
    Posts
    30

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Sorry for the double post. I wasn't aware that messages had to be approved by an administrator, didn't see the first show up, so I posted again. I'm still looking for a way to add additional properties to the collection that more uniquely identify each client, such as usernames, etc. and eventually a database backend that stores email accounts, passwords, and other information to be used at login. Here's a screen shot of what I've done with your amazing library so far:

    3 Clients Connected:
    http://imgur.com/skWr4

    1 Client Connected, 2 Disconnected Clients Closed:
    http://imgur.com/Y0Lnl

    Server Shutdown, 1 Disconnected Client Open:
    http://imgur.com/NB71E

    I've customized my GUI quite a bit. The Start and Stop buttons aren't necessary anymore since the socket is opened when the application is executed. I may reuse them as "Load" and "Refresh" buttons for my database back-end when I get it finished. Thanks again!
    Last edited by yfzpurgatory; Sep 9th, 2012 at 03:06 AM.

  17. #177
    Junior Member
    Join Date
    Sep 2012
    Posts
    30

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Hey, jmc. Awesome wrapper. I've been beating my head against a wall trying to get some type of secure asynchronous connectivity going for the last 2 and a half days. I've blazed through about a dozen different tutorials without even a remote understanding of Socket networking.

    I only have one question. I'm going to use this (with full referencing leading back to you which I'll probably contact you some time in the future about) to write a text-based MMO, and I need some way of storing a large amount of variables or properties in the List that stores the connection information. Is there a way to go about doing this without utterly destroying your library (rewriting it or amending it)? I'm getting a little lost on how the connection information is handled and how its passed through each method, how to sort through the List to find a particular connection that you want without utilizing a ListView or other control, etc.

    I greatly appreciate any help you can give me. Once again, awesome job on this. I got a server and multiple clients connecting and disconnecting without any issues in a matter of minutes.

  18. #178

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    @yfzpurgatory, I'm glad that you found my demo useful, as that's exactly why I created it in the first place. One good thing about this being posted on a forum is that I get a notification if anyone posts to this thread, so it's easier to keep adding and providing help if required. I haven't actually touched the code for a while though, so I'm not as familiar with it as I used to be. In theory, you should simply be able to add extra properties to the HostInfo type and everything will continue to work exactly as it does now. Adding is not a problem. It's only if you remove something that you might break existing code.

    If I remember correctly, HostInfo is a structure. If you do want to extend the HostInfo type then it may be more appropriate to implement it as a class instead. If you were going to do that then you may have to review how it's used to make sure that the change from a value type to a reference type didn't cause any issues. If it did then you could still make the change but just change the way you handle instances.

    There could be various ways to implement the searching you suggest but some of them may require changes to existing code. If you want to stick with the List(Of HostInfo) then you can use LINQ something like this:
    vb.net Code:
    1. Dim match = myList.FirstOrDefault(Function(o) o.Name = name)
    2.  
    3. If match <> Nothing Then

  19. #179
    Junior Member
    Join Date
    Sep 2012
    Posts
    30

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    @jmc, I was looking at the library and the HostInfo type and it doesn't look like there would be an issue adding Username, Password, etc. and since it is a type, I could utilize Random Access Files to store and retrieve information until I get more comfortable with it. I'm pretty new to OOP as I stated above, so it may take me a while to get things how I would like them. As you can see from the pictures, I've done quite a bit already.

    I've thought about making a separate Type to store usernames and all of that and index through and assign the information to them by use of the ConnectionEvent's IndexOf property like I did with my ListView:
    Code:
    Private Sub server_ConnectionClosed(sender As Object, e As Wunnell.Net.ConnectionEventArgs) Handles server.ConnectionClosed
            Dim tempClient = e.Host
            Me.clients.Remove(tempClient)
            Me.RemoveFromList(tempClient.ToString)
            Me.UpdateLog("SERVERINFO" & SEP_CHAR & "Connection closed from " & tempClient.ToString & " @ " & Date.Now)
    
            Connected = Connected - 1
            Me.UpdateConnectedLabel(Connected)
        End Sub
    
        Private Sub RemoveFromList(ByVal user As String)
            lsvClients.Items.RemoveAt(user.IndexOf(user))
        End Sub
    But there's going to be inherent problems associated with doing it that way. An example would be, "User 1 private messages User 2." In this case, User 1 will receive an instant response because the server has his/her connection info readily available through ConnectionEventArgs; User 2's information, however, will have to be pulled through a unique identifier. Do you have any suggestions?
    Last edited by yfzpurgatory; Sep 9th, 2012 at 03:30 AM.

  20. #180

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    There's actually already the NetworkCredential class that you could use, although it might have a little more functionality than you actually need. If you want to use that type or define your own, you could then add a Credential property to the HostInfo type and assign an instance of your type to that.

  21. #181
    Junior Member
    Join Date
    Sep 2012
    Posts
    30

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Adding a Credential property to HostInfo and assigning an instance of my custom type to it sounds like it would work perfectly. Is there any way that you could create a Credential property for me (I have no idea what it is or how to use it), comment it, and show me how to utilize it in conjunction with another Type? I'm not trying to be stingy with your time, but MSDN isn't exactly explicit about what things do.

  22. #182

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    You already know how to do it. You can see how the HostInfo type is defined so defining a Credential type will be exactly the same. As for adding a property to HostInfo, it will be exactly the same as the properties it already contains.

  23. #183
    Junior Member
    Join Date
    Sep 2012
    Posts
    30

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    I'm not aware of what a credential is or how it is used; I haven't seen or used terminology like "delegate", "invoking", or "credentials" in any previous applications, so its pretty foreign to me. As for editing your library I'm going to see what I can do. Can your Type be used to store and access data in a RAF like any other type, or has that changed too since VB6?

  24. #184

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    In a programming context, a user's credentials are basically their user name and password.

    I'm not familiar with the term RAF but, from what I can see, it's some sort of file type. In VB.NET you would use a DLL if you want a type library that can be used in multiple applications or to segregate certain functionality from the main application.

  25. #185
    Junior Member
    Join Date
    Sep 2012
    Posts
    30

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Ah, okay. Yes, RAF stands for Random Access File. It's more than likely an outdated technique of using Types to store and collect data from files. I haven't attempted it yet but I feel certain that I can add what I want to your library and it'll work. I'll just have to use the connection information to sort through the HostInfo list to find a connection with a specific username as that is how clients will ultimately be uniquely identified in a chat or game setting, or rather how they will be visually represented on screen.

    Thanks for the help, once again. I think I got it from here, and like I've said, your library works wonderfully. I've had no hangups in its implementation; the built in error handling is superb.

    p.s. I'd rather ask here since this deals with your code and how you implemented it in your example with a MDI Parent. My MDI Parent does all of the connection work; it connects, sends, and receives messages. However, I have a child form that visually represents the data received. Here's the code:

    Code:
    Private Sub client_MessageReceived(sender As Object, e As Wunnell.Net.MessageReceivedEventArgs) Handles client.MessageReceived
            Dim tempData() As String = e.Message.ToString.Trim.Split("|")
            Select Case tempData(0)
                Case "GLOBALCLIENTMSG"
                    UpdateLog("GLOBALCLIENTMSG", tempData(1).Trim, tempData(2).Trim)
            End Select
        End Sub
    
        Public Sub UpdateLog(ByVal msgtype As String, ByVal text As String, ByVal user As String)
            Select Case msgtype.Trim
                Case "SERVERINFO"
                    frmChat.rtbChat.SelectionColor = Color.Blue
                    frmChat.rtbChat.AppendText("Info: ")
                    frmChat.rtbChat.SelectionColor = Color.Black
                    frmChat.rtbChat.AppendText(text.Trim & ControlChars.NewLine)
                    frmChat.rtbChat.ScrollToCaret()
                Case "SERVERMSG"
                    frmChat.rtbChat.SelectionColor = Color.Aqua
                    frmChat.rtbChat.AppendText("Server: ")
                    frmChat.rtbChat.SelectionColor = Color.Black
                    frmChat.rtbChat.AppendText(text.Trim & ControlChars.NewLine)
                    frmChat.rtbChat.ScrollToCaret()
                Case "GLOBALCLIENTMSG"
                    frmChat.rtbChat.SelectionColor = Color.Blue
                    frmChat.rtbChat.AppendText("[" & user.Trim & "]: ")
                    frmChat.rtbChat.SelectionColor = Color.Black
                    frmChat.rtbChat.AppendText(text.Trim & ControlChars.NewLine)
                    frmChat.rtbChat.ScrollToCaret()
            End Select
        End Sub
    In VB6, we could call any form from the MDI Parent and ask it to perform a task and it would be done. In VB 2010, I've read that you have to ask whether an Invoke is needed and if so, use a delegate method to perform the action. This is extremely confusing for me. You can see what I've done, frmChat.rtbChat.AppendText. I've made sure that data is being handled exactly how I wanted it to and it gets all the way through the Select Case statement; the problem is that it is not being written to the RichTextBox on the child form.

    Could you offer some advice or point me in the direction of a tutorial involving delegates and cross-form/thread operations? Thanks again.

  26. #186

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Quote Originally Posted by yfzpurgatory View Post
    Ah, okay. Yes, RAF stands for Random Access File. It's more than likely an outdated technique of using Types to store and collect data from files. I haven't attempted it yet but I feel certain that I can add what I want to your library and it'll work. I'll just have to use the connection information to sort through the HostInfo list to find a connection with a specific username as that is how clients will ultimately be uniquely identified in a chat or game setting, or rather how they will be visually represented on screen.
    The term "random access file" doesn't really get used in .NET because all files can be accessed randomly and it's only at the application level that you might limit that. In .NET you can use various types of streams, readers and writers to read and write files in different ways but there's always a FileStream underneath anything else you may use and a FileStream inherently allows you to access any position in the file at random.

    To locate a particular user's connection information in a List(Of HostInfo) might look like this:
    Code:
    Dim userInfo = hostInfos.SingleOrDefault(Function(hi) hi.UserName = userName)
    
    If userInfo <> Nothing Then
    Quote Originally Posted by yfzpurgatory View Post
    Thanks for the help, once again. I think I got it from here, and like I've said, your library works wonderfully. I've had no hangups in its implementation; the built in error handling is superb.

    p.s. I'd rather ask here since this deals with your code and how you implemented it in your example with a MDI Parent. My MDI Parent does all of the connection work; it connects, sends, and receives messages. However, I have a child form that visually represents the data received.

    In VB6, we could call any form from the MDI Parent and ask it to perform a task and it would be done. In VB 2010, I've read that you have to ask whether an Invoke is needed and if so, use a delegate method to perform the action. This is extremely confusing for me. You can see what I've done, frmChat.rtbChat.AppendText. I've made sure that data is being handled exactly how I wanted it to and it gets all the way through the Select Case statement; the problem is that it is not being written to the RichTextBox on the child form.

    Could you offer some advice or point me in the direction of a tutorial involving delegates and cross-form/thread operations? Thanks again.
    Having to call Invoke and use a delegate has nothing specific to do with MDI forms. That is only required when you are executing code on a thread other than the UI thread and then want to get data from or to the UI. It's crossing the thread boundary to access a control that requires invoking a delegate.

    Your first issue is that you are using the default instance. Follow the Blog link in my signature and check out my post on Default Form Instances to learn what they are and why they can't help you in this scenario. To learn how to access the UI correctly from a secondary thread, follow the CodeBank link in my signature and check out my thread on Accessing Controls From Worker Threads.

  27. #187
    Junior Member
    Join Date
    Sep 2012
    Posts
    30

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    I'm actually using a new instance of the form. Here's the call:
    Code:
    Private Sub StartChatToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles StartChatToolStripMenuItem.Click
            Call New frmChat() With {.MdiParent = Me}.Show()
            StartChatToolStripMenuItem.Enabled = False
    End Sub
    As you can see it was taken directly from your own MDIParent and children forms in your example. I browsed through your BackgroundWorker and default instance tutorails; I do not feel that multi-threading is really relevant. I'm going to look into using delegates.

    Edit:
    I didn't have to use a background worker or delegates. The error in using "Call New" is that you aren't identifying the form and thus can't use it on the UI thread, from what I understand.. even if you do use delegates. I'm using this instead and it works perfectly now:

    Setting chlChat as our new instance.
    Code:
    Public Class mdiMain
        Public chlChat As New frmChat()
    Loading chlChat and using it:
    Code:
    Private Sub StartChatToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles StartChatToolStripMenuItem.Click
            chlChat.MdiParent = Me
            chlChat.Show()
            StartChatToolStripMenuItem.Enabled = False
        End Sub
    
        Public Sub UpdateLog(ByVal msgtype As String, ByVal text As String, ByVal user As String)
            Select Case msgtype.Trim
                Case "SERVERINFO"
                    chlChat.rtbChat.SelectionColor = Color.Blue
                    chlChat.rtbChat.AppendText("Info: ")
                    chlChat.rtbChat.SelectionColor = Color.Black
                    chlChat.rtbChat.AppendText(text.Trim & ControlChars.NewLine)
                    chlChat.rtbChat.ScrollToCaret()
                Case "SERVERMSG"
                    chlChat.rtbChat.SelectionColor = Color.Aqua
                    chlChat.rtbChat.AppendText("Server: ")
                    chlChat.rtbChat.SelectionColor = Color.Black
                    chlChat.rtbChat.AppendText(text.Trim & ControlChars.NewLine)
                    chlChat.rtbChat.ScrollToCaret()
                Case "GLOBALCLIENTMSG"
                    chlChat.rtbChat.SelectionColor = Color.Blue
                    chlChat.rtbChat.AppendText("[" & user.Trim & "]: ")
                    chlChat.rtbChat.SelectionColor = Color.Black
                    chlChat.rtbChat.AppendText(text.Trim & ControlChars.NewLine)
                    chlChat.rtbChat.ScrollToCaret()
            End Select
        End Sub
    And a picture of it all working:
    http://imgur.com/9So0V
    Last edited by yfzpurgatory; Sep 10th, 2012 at 12:14 AM.

  28. #188

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Originally, you were explicitly creating a new instance of the form when displaying it but, as you have correctly said, you were not keeping a reference to that instance and could therefore not access it later. When you were trying to update the form you were in fact using the default instance. You were successfully updating a form instance but it was not the same form instance that you had displayed to the user. It was the default instance for the secondary thread that you were executing on, which had never been displayed to the user at all.

  29. #189
    Junior Member
    Join Date
    Sep 2012
    Posts
    30

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Exactly.

    Edit:
    I successfully added the property Username to HostInfo. It wasn't difficult or overly complicated. I can't exactly explain what I did wrong, but it had to do with trying to add it to another project without rebuilding the .dll, and trying to use HostInfo in a separate project that was still using the old .dll. I fixed it by copying the project files into my project folder, adding it to my solution, rebuild it after alterations, and make sure I removed the reference for the old DLL and add the reference for the new DLL.

    Works perfectly. I'll have some screen shots soon.

    Edit2:
    I removed the username property from HostInfo. I couldn't get updating to work for the list, so I'm using the ListView instead. I'm going to have to compare a lot of things against a lot of things to eventually get data from a file, but I know how to do it; just worried that it'll take too much processing power away from everything else. Thanks again for the library. I highly doubt I'll be posting here again. I'll message you later in order to get referencing information for when the project is complete so that you receive proper credit.
    Last edited by yfzpurgatory; Sep 11th, 2012 at 03:39 PM.

  30. #190
    Junior Member
    Join Date
    Sep 2012
    Posts
    30

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Here's a screen shot of what I've done with it:

  31. #191
    Addicted Member
    Join Date
    Jan 2007
    Posts
    199

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Quote Originally Posted by jmcilhinney View Post
    I would have to test to work that out, which I can't do right now, but the first thing that springs to mind is that the port number changes.
    Hi jmcilhinney I just like to raise this issue again been banging my head to fix this but I could find solution, I step over on each line of code to check when client click reconnect it does nothing. Below is the code where error occur. Port and Address Still has value even client was dicconected.

    Code:
    Private Sub Connect(ByVal ar As IAsyncResult)
            Try
                'Complete the asynchronous connection.
                Me.client.EndConnect(ar) ' < ----- This line error occur (A connect request was made on an already connected socket)
    
                'Get the port that was assigned to the local end point.
                Me._localPort = DirectCast(Me.client.Client.LocalEndPoint, IPEndPoint).Port
    
                Me.stream = Me.client.GetStream()
    
                Dim buffer(Me.BufferSize - 1) As Byte
    
                'Listen asynchronously for an incoming message.
                Me.stream.BeginRead(buffer, 0, Me.BufferSize, AddressOf Read, buffer)
    
                'Notify any listeners that the connection was successful.
                Me.OnConnectionAccepted(New ConnectionEventArgs(Me.server))
            Catch ex As SocketException
                'The specified server was not found.
                Me.OnConnectionFailed(New ConnectionEventArgs(Me.server))
            End Try
        End Sub

  32. #192
    Addicted Member
    Join Date
    Jan 2007
    Posts
    199

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Hi jmcilhinney please need help... Still issue about client disconnect and reconnect. can you please help how to initialize connection when client reconnect. Below is the code what I'm trying to accomplish but I'm having same error. I'm out of idea right now been trying to solve this since the last time I posted my last question.

    Public Sub Connect()
    Try
    If Me.isDisposed Then
    'MyBase.New(BufferSize, Encoding)
    Me.Initialise(Me.server.HostName, Me.server.Port)
    Me.client.BeginConnect(Me.server.HostName, Me.server.Port, AddressOf Connect, Nothing)
    Else

    'Connect asynchronously to the server.
    Me.client.BeginConnect(Me.server.HostName, Me.server.Port, AddressOf Connect, Nothing)
    End If
    Catch ex As SocketException

    End Try
    End Sub

    Error :
    Cannot access a disposed object.
    Object name: 'System.Net.Sockets.Socket'.

  33. #193
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    The object is disposed and yet you are still calling its methods. When an object is disposed its done, you can't continue using it.

    vbnet Code:
    1. If Me.isDisposed Then
    2. 'MyBase.New(BufferSize, Encoding)
    3. Me.Initialise(Me.server.HostName, Me.server.Port)
    4. Me.client.BeginConnect(Me.server.HostName, Me.server.Port, AddressOf Connect, Nothing)

    The above code is just blasphemous. You just don't do that....ever
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  34. #194
    Addicted Member
    Join Date
    Jan 2007
    Posts
    199

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Quote Originally Posted by Niya View Post
    The object is disposed and yet you are still calling its methods. When an object is disposed its done, you can't continue using it.

    vbnet Code:
    1. If Me.isDisposed Then
    2. 'MyBase.New(BufferSize, Encoding)
    3. Me.Initialise(Me.server.HostName, Me.server.Port)
    4. Me.client.BeginConnect(Me.server.HostName, Me.server.Port, AddressOf Connect, Nothing)

    The above code is just blasphemous. You just don't do that....ever
    Hi! Niya thanks for the reply yes your correct it's already dispose, what i'm trying to do is to re initialize new socket and right now I'm stack with it I have no Idea how to do it. Can you help me out?

  35. #195
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    You cannot re-initialize a disposed object. If any class allowed this it would be a bad design. You simple create a new one, or you don't dispose of it in the first place.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  36. #196
    Junior Member
    Join Date
    Sep 2012
    Posts
    30

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Hey, Jmc. I encountered an issue when I upgraded to VS Professional 2010. Everything was going just fine until then. The error is on the client side when I'm closing the application:

    Cannot access a disposed object.
    Object name: 'System.Net.Sockets.NetworkStream'.

    It occurs in MessageClient.vb and is in the Read method. Running the application as release and/or without debugging returns no errors and everything runs just fine. Is there any insight you can give me into why this is happening?

    Edit: I'm assuming there needs to be some type of graceful closing that needs to happen, because I've been able to error the server and the client depending on where I dispose of the client object. When I don't dispose of the client object, the server will error in MessageServer on the Read line. I'm honestly not to sure as I haven't ripped your source apart and have used it as is. Thanks for the help.
    Last edited by yfzpurgatory; Oct 6th, 2012 at 12:09 AM.

  37. #197

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Quote Originally Posted by yfzpurgatory View Post
    Hey, Jmc. I encountered an issue when I upgraded to VS Professional 2010. Everything was going just fine until then. The error is on the client side when I'm closing the application:

    Cannot access a disposed object.
    Object name: 'System.Net.Sockets.NetworkStream'.

    It occurs in MessageClient.vb and is in the Read method. Running the application as release and/or without debugging returns no errors and everything runs just fine. Is there any insight you can give me into why this is happening?

    Edit: I'm assuming there needs to be some type of graceful closing that needs to happen, because I've been able to error the server and the client depending on where I dispose of the client object. When I don't dispose of the client object, the server will error in MessageServer on the Read line. I'm honestly not to sure as I haven't ripped your source apart and have used it as is. Thanks for the help.
    There are various situations where, as far as I can tell, the only way to be notified at one end that the other end has disconnected is to catch an exception. I have done that in some cases in the existing code but it hasn't been tested rigorously so there may be others. It sounds like you may have encountered one.

    All I can suggest is test repeatedly to make sure that you understand under exactly what circumstances the exception is being thrown and what exception it is and, if you cannot prevent it, add the appropriate exception handling to your code. That's exactly what I would do.

  38. #198
    Junior Member
    Join Date
    Sep 2012
    Posts
    30

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Here's the disassembly:

    Code:
    00000080  mov         dword ptr [ebp-24h],eax
    The error is occurring on this line:

    Code:
    'Complete the asynchronous read and get the first block of data.
    Dim byteCount = Me.stream.EndRead(ar)
    Since that line is inside of a Try statement, all I would need to do is add a Catch ex As statement line for IO.NetworkStream, right?

    Edit: You already had it setup to catch an IOException, so I simply added Exit Sub (very distasteful way of handling it) to the Catch:

    Code:
           Catch ex As IOException
                Exit Sub
                'The callback specified when BeginRead was called may get invoked one last time when the TcpClient is disposed.
                'This exception is thrown when EndRead is called on a disposed client stream.
            End Try
    Seems to work just fine now. In fact, the application was doing exactly what your comment says may happen. I also had to add in the following:

    NullReferenceException and ObjectDisposedException. Seems to be fine now. When I have the time, I'm going to have to go through your code more thoroughly and find out why a disposed object is being called to begin with.
    Last edited by yfzpurgatory; Oct 6th, 2012 at 01:33 AM.

  39. #199
    Addicted Member
    Join Date
    Jan 2007
    Posts
    199

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Quote Originally Posted by yfzpurgatory View Post
    Here's the disassembly:

    Code:
    00000080  mov         dword ptr [ebp-24h],eax
    The error is occurring on this line:

    Code:
    'Complete the asynchronous read and get the first block of data.
    Dim byteCount = Me.stream.EndRead(ar)
    Since that line is inside of a Try statement, all I would need to do is add a Catch ex As statement line for IO.NetworkStream, right?

    Edit: You already had it setup to catch an IOException, so I simply added Exit Sub (very distasteful way of handling it) to the Catch:

    Code:
           Catch ex As IOException
                Exit Sub
                'The callback specified when BeginRead was called may get invoked one last time when the TcpClient is disposed.
                'This exception is thrown when EndRead is called on a disposed client stream.
            End Try
    Seems to work just fine now. In fact, the application was doing exactly what your comment says may happen. I also had to add in the following:

    NullReferenceException and ObjectDisposedException. Seems to be fine now. When I have the time, I'm going to have to go through your code more thoroughly and find out why a disposed object is being called to begin with.
    Same issue here VS2010, I haven't time to get back to the code to not disposed the client when server get closed so client can re connect again.

  40. #200
    New Member
    Join Date
    Nov 2012
    Posts
    11

    Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient

    Hi,
    I am using VS2008 Express.
    When I attempt to connect the client, I get the following message box:
    "The specified server could not be found. Would you like to try again?"
    Please could you let me know what is wrong.
    Many Thanks

Page 5 of 7 FirstFirst ... 234567 LastLast

Posting Permissions

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



Click Here to Expand Forum to Full Width