Page 2 of 7 FirstFirst 12345 ... LastLast
Results 41 to 80 of 273

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

  1. #41
    Hyperactive Member
    Join Date
    Jun 2005
    Posts
    265

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

    Quote Originally Posted by jmcilhinney View Post
    The code uses various VB 2008 and .NET 3.5 features. You could certainly implement the same functionality in VB 2005 but you'd have to use loops where I've used LINQ queries, etc.
    Thank's alot bro.
    I will appreciate it if you could help me in following problem:
    I made a program in vb.net 2005, it using Winsock DLL. Here is the full explanation of it:
    http://www.vbforums.com/showthread.php?t=590966


    every body told me that problem is from Winsock Dll. However, I downloaded VB.Net 2008 Express Edition, only to test the same program but by using your class. unfortunately, the same problem appear!

    Attached the modified project which using your class instead of Winsock Dll.

    Thank's in advance
    Attached Files Attached Files

  2. #42
    Member
    Join Date
    Nov 2009
    Posts
    39

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

    Hello,
    i'am trying to use your Class in Console.
    But i have several bugs during devugging like :
    La référence d'objet n'est pas définie à une instance d'un objet.
    Object reference not set to an instance of an object.
    On Connection Event.

  3. #43

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

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

    Quote Originally Posted by Ianis View Post
    Hello,
    i'am trying to use your Class in Console.
    But i have several bugs during devugging like :


    On Connection Event.
    You'd have to be much more specific. Exactly what line and exactly what reference is Nothing? Also, I've not had such issues so I'd need to know exactly how the code is being used.

  4. #44
    Member
    Join Date
    Nov 2009
    Posts
    39

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

    Quote Originally Posted by jmcilhinney View Post
    You'd have to be much more specific. Exactly what line and exactly what reference is Nothing? Also, I've not had such issues so I'd need to know exactly how the code is being used.
    There are several Errors which, i think are cause beceause there are no from anymore.
    I only tryed to turn the Server into Console.
    I am sure my code is good, also errors comes from the class's.

    You should try your Server in console.

  5. #45

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

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

    Quote Originally Posted by Ianis View Post
    There are several Errors which, i think are cause beceause there are no from anymore.
    I only tryed to turn the Server into Console.
    I am sure my code is good, also errors comes from the class's.

    You should try your Server in console.
    As should be the case with a class library, that DLL is totally independent of what is using it. It doesn't care whether the application using it is a windows app, a console app or whatever. If the library is throwing exceptions it's nothing to do with it being used by a console app specifically. Either there's a bug in my code or you're using it incorrectly. There's nothing wrong with a library throwing exceptions. If it is forced into exceptional situations it should throw exceptions. You need to either debug your code and stop it doing the wrong thing or, if it's a situation beyond your control, handle the exceptions and react accordingly. If you can tell me where the issue is then I can check to see whether it's an issue with my code.

  6. #46
    New Member avatar_nz's Avatar
    Join Date
    Dec 2009
    Posts
    2

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

    Firstly, thanks for the source and original post. Simply awesome!
    I wrote a tcp client application (using Socketwrench .Net) in VB 2005 back in '07 that I am looking to re-write. I have had a quick look through your source and played around with a few things. I would like to use your code as the basis of my re-write. The problem area I had with the original was/is efficient handling of the returned messages. Each message is encapsulated in xml tags (although, they are not true xml). My original version used a loop until the closing tag was found before sending the message off to a message handling routine (this was a VB6 conversion). I'm sure that using string is probably an in-efficient method given the advances in the framework?
    Cheers

  7. #47

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

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

    Quote Originally Posted by avatar_nz View Post
    Firstly, thanks for the source and original post. Simply awesome!
    I wrote a tcp client application (using Socketwrench .Net) in VB 2005 back in '07 that I am looking to re-write. I have had a quick look through your source and played around with a few things. I would like to use your code as the basis of my re-write. The problem area I had with the original was/is efficient handling of the returned messages. Each message is encapsulated in xml tags (although, they are not true xml). My original version used a loop until the closing tag was found before sending the message off to a message handling routine (this was a VB6 conversion). I'm sure that using string is probably an in-efficient method given the advances in the framework?
    Cheers
    Glad to help. I'm just not sure whether you're actually asking a question there or not. If you're saying that you want to pass XML messages back and forth then you might want to use the XmlDocument.LoadXml method to load the received String into an XmlDocument. To create the String from the XmlDocument in the first place you could use the XmlDocument.Save method and pass a StringWriter, which is like a StreamWriter but writes to a String instead of a Stream.

  8. #48
    Member
    Join Date
    Nov 2009
    Posts
    39

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

    I found what's going wrong :

    it's a Console Application, so this need a
    Code:
    Sub Main()
    
    End Sub
    But..
    With your class i need to add this in a Sub :
    ByVal Sender As Object, ByVal e As MessageReceivedEventArgs

    Code:
        Sub Main(ByVal Sender As Object, ByVal e As MessageReceivedEventArgs)
            AddHandler server.MessageReceived, AddressOf MessageRecieved
    
            Console.ReadLine()
        End Sub
    But i cant add this to the Main Sub

    No accessible 'Main' method with an appropriate signature was found
    Last edited by Ianis; Dec 4th, 2009 at 07:45 PM.

  9. #49
    New Member avatar_nz's Avatar
    Join Date
    Dec 2009
    Posts
    2

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

    Thanks John. I will will have a play around with this and some of the other great information from your blogs.
    Cheers

  10. #50

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

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

    Quote Originally Posted by Ianis View Post
    I found what's going wrong :

    it's a Console Application, so this need a
    Code:
    Sub Main()
    
    End Sub
    But..
    With your class i need to add this in a Sub :
    ByVal Sender As Object, ByVal e As MessageReceivedEventArgs

    Code:
        Sub Main(ByVal Sender As Object, ByVal e As MessageReceivedEventArgs)
            AddHandler server.MessageReceived, AddressOf MessageRecieved
    
            Console.ReadLine()
        End Sub
    But i cant add this to the Main Sub
    You're quire correct that you need a procedure with that signature but it's not supposed to be the Main method. Your own code is saying that it's supposed to be a method named MessageReceived that has that signature, so why do you need to add those parameters to the Main method?
    Code:
    Sub Main()
        AddHandler server.MessageReceived, AddressOf MessageRecieved
    
        Console.ReadLine()
    End Sub
    
    Sub MessageRecieved(ByVal Sender As Object, ByVal e As MessageReceivedEventArgs)
        '...
    End Sub

  11. #51
    Member
    Join Date
    Nov 2009
    Posts
    39

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

    Well ok but,
    do you have a simple exemple of a ModMain in Console.
    Just few lines HOWTO replace the Server Main Form > Console
    (The most simple you can do with console.writeline / debug.print )

  12. #52

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

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

    Quote Originally Posted by Ianis View Post
    Well ok but,
    do you have a simple exemple of a ModMain in Console.
    Just few lines HOWTO replace the Server Main Form > Console
    (The most simple you can do with console.writeline / debug.print )
    To be honest, I really don't see that this is appropriate for a Console app anyway. The whole point of this code is its asynchronous nature, which allows communication to take place in the background while the main thread remains responsive. That's not an issue with a Console app. In fact, if you send off other threads to do the work your app is simply going to exit because the main thread will complete immediately.

  13. #53
    Member
    Join Date
    Nov 2009
    Posts
    39

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

    Do you think there is a way for Make the Server in console ?
    Cause the protocol i'm working on make server without Send Message from Server.
    The Server is just like a IRC Server.
    Something which allow each client chatting together.
    But i prefere have a Console application for a such thing.

    I'll explain better if you don't udnerstand

    Thanks, Ianis.

  14. #54

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

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

    Quote Originally Posted by Ianis View Post
    Do you think there is a way for Make the Server in console ?
    Cause the protocol i'm working on make server without Send Message from Server.
    The Server is just like a IRC Server.
    Something which allow each client chatting together.
    But i prefere have a Console application for a such thing.

    I'll explain better if you don't udnerstand

    Thanks, Ianis.
    Beyond the scope of this thread.

  15. #55
    Junior Member rydinophor's Avatar
    Join Date
    Jul 2009
    Location
    Missouri, USA
    Posts
    18

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

    Sorry for the necro post, but that DLL file of yours needs a small edit, Every time a client disconnects unsafely the server crashes, here's where the following bug is located:
    Location: Wunnell.Net.MessageClientServer->MessageServer.vb
    vb Code:
    1. ''' <summary>
    2.     ''' Receives an incoming message.
    3.     ''' </summary>
    4.     ''' <param name="ar">
    5.     ''' Contains state information for the read operation.
    6.     ''' </param>
    7.     Private Sub Read(ByVal ar As IAsyncResult)
    8.         Dim asyncState = DirectCast(ar.AsyncState, ReadAsyncState)
    9.         Dim buffer = asyncState.Buffer
    10.         Dim client = asyncState.Client
    11.  
    12.         Try
    13.             Dim stream = client.GetStream()
    14.  
    15.             'Complete the asynchronous read and get the first block of data.
    16.             Dim byteCount = stream.EndRead(ar)
    17.  
    18.             If byteCount = 0 Then
    19.                 'If there is no data when an asynchronous read completes it is because the client closed the connection.
    20.                 Me.RemoveClient(client)
    21.             Else
    22.                 'Start building the message.
    23.                 Dim message As New StringBuilder(Me.Encoding.GetString(buffer, 0, byteCount))
    24.  
    25.                 'As long as there is more data...
    26.                 While stream.DataAvailable
    27.                     '...read another block of data.
    28.                     byteCount = stream.Read(buffer, 0, Me.BufferSize)
    29.  
    30.                     'Build the message block by block.
    31.                     message.Append(Me.Encoding.GetString(buffer, 0, byteCount))
    32.                 End While
    33.  
    34.                 'Listen asynchronously for another incoming message.
    35.                 stream.BeginRead(buffer, 0, Me.BufferSize, AddressOf Read, New ReadAsyncState With {.Client = client, .Buffer = buffer})
    36.  
    37.                 'Notify any listeners that a message was received.
    38.                 Me.OnMessageReceived(New MessageReceivedEventArgs(Me.clients(client), message.ToString()))
    39.             End If
    40.         Catch ex As InvalidOperationException
    41.             'The callback specified when BeginRead was called gets invoked one last time when the TcpListener is stopped.
    42.             'This exception is thrown when GetStream is called on a disconnected client or EndRead is called on a disposed stream.
    43.         End Try
    44.     End Sub
    I seemed to solve the issue by simply changing:
    vb Code:
    1. Catch ex As InvalidOperationException
    To the following:
    vb Code:
    1. Catch ex As System.IO.IOException
    2.                 Me.RemoveClient(client)

    Either My Computer Is Messed up or that Current Exception is pointless, it told me to use the system.io exception and it fixed it in a flash.
    If you want to you might want to change to the System.IO exception because the current exception fails to work.

    Also The Error Is thrown here and fails to proceed to the exception:
    Dim byteCount = stream.EndRead(ar)

    P.S. I'm counting on this library for my Pokemon game I'm creating, The client side is in Purebasic, and The Server is in VB.net.

    Regards,
    Rydinophor

    EDIT:
    Also, Would You happen to give an example of your server multithreaded? I'm stumped on this part, My friend who is coding with me is confusing me with multithreading with the server side, and I'm completely lost, My idea is throw the recieved data packet onto a thread and have it handle that and continue processing the other packets coming in. I'm quite new to VB.net, I just began last summer.

    With Regards,
    Rydinophor
    Last edited by rydinophor; Dec 19th, 2009 at 09:36 PM.

  16. #56
    Member freedompeace's Avatar
    Join Date
    Oct 2009
    Posts
    48

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

    My modified code doesn't send files properly; the files become corrupted.

  17. #57
    Master Of Orion ForumAccount's Avatar
    Join Date
    Jan 2009
    Location
    Canada
    Posts
    2,802

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

    So I pretty much ran this project "straight out of the box", all I did was add a button on the ClientWindow that runs this code when it's clicked:

    vb.net Code:
    1. For counter As Integer = 0 To 1000
    2.     Me.client.Send(counter.ToString())
    3. Next

    Attached is how the server will receive it. It's easy to see what is happening to the data, but my question is how can this be prevented? I want each number to be received on a separate line. So each message is processed separately, is this possible?
    Attached Images Attached Images  

  18. #58

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

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

    Quote Originally Posted by ForumAccount View Post
    So I pretty much ran this project "straight out of the box", all I did was add a button on the ClientWindow that runs this code when it's clicked:

    vb.net Code:
    1. For counter As Integer = 0 To 1000
    2.     Me.client.Send(counter.ToString())
    3. Next

    Attached is how the server will receive it. It's easy to see what is happening to the data, but my question is how can this be prevented? I want each number to be received on a separate line. So each message is processed separately, is this possible?
    Check whether each string you receive has a null character terminating it. If it does, edit your server to detect that null character and treat that as the end of a message. If there is no null character, edit your client to add one.

  19. #59
    New Member
    Join Date
    Oct 2007
    Posts
    5

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

    First, I have to say, I *love* your post. This is the absolute easiest implementation of a TCP client/server I've seen in .Net. Using your methods I got stuff sending back and forth in 5 minutes. Question though, when I don't use your client's send method, and I connect to the TCP server with telnet... the received message is always garble unless a ascii 10/13 (it looks like the same character is reported regardless of what I type in the telnet window)... is there a quick reason why that's the case (like... does it always require a line terminator and if it doesn't get it in the message it doesn't work)?

    Btw, this code rocks. The last time I needed TCP/IP I used the WinSock control with VB6. I used a delimited protocol and parsed everything. I know XML is kind of talky, but it makes creating simple protocol's soooooo easy with serialization. I have a simple chat client and shared browser (so two people can browse together) setup (Note: this is just a hobby project, I'm aware of the security implications if I were to implement some of these commands, it was more of just a test). I have a serialization class that's not shown here that I use.. but it's a good example of how you can easily couple this with your client (I send the XML and then deserialize it when it's received... it looks for the end marker to know the trasmission is done). I also did this in about 10 minutes so I haven't thought it out further. ;P

    Code:
    Imports Iuf.Extensions
    
    ''' <summary>
    ''' Shared Browser Protocol
    ''' </summary>
    ''' <remarks></remarks>
    Public Class Protocol
    
        Private Const END_MARKER As String = "#END"
        Private Const PROTOCOL_VERSION = 1
    
        Public Shared Function ParseInput(ByVal xml As String) As Message
            xml = xml.Trim(END_MARKER)
            Dim msg As Message = Iuf.Utilities.Serialization.XMLToObject(Of Message)(xml)
            Return msg
        End Function
    
        Public Shared Function AddEndMarkerToXml(ByVal xml As String) As String
            xml += END_MARKER
            Return xml
        End Function
    
        Public Shared Function ToXml(ByVal msg As Message) As String
            Return Iuf.Utilities.Serialization.ObjectToXML(msg) & END_MARKER
        End Function
    
        Public Shared Function ToMessage(ByVal xml As String) As Message
            Return ParseInput(xml)
        End Function
    
        <Serializable()> _
        Public Class Message
    
            Sub New()
    
            End Sub
    
            Enum Commands
                Chat
                Identify
                Click
                DoubleClick
                ShareUrl
                GotoUrl
                PhotoUrl
                SetWindowTitle
                MoveWindow
                MaximizeWindow
                MinimizeWindow
            End Enum
    
            Private _command As Commands
            Public Property Command() As Commands
                Get
                    Return _command
                End Get
                Set(ByVal value As Commands)
                    _command = value
                End Set
            End Property
    
            Private _arguments As New List(Of String)
            Public Property Arguments() As List(Of String)
                Get
                    Return _arguments
                End Get
                Set(ByVal value As List(Of String))
                    _arguments = value
                End Set
            End Property
    
        End Class
    
    End Class
    Last edited by jinx101; Jan 23rd, 2010 at 04:37 PM.

  20. #60
    New Member
    Join Date
    Oct 2007
    Posts
    5

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

    Any thoughts on my telnet question?

  21. #61
    Junior Member rydinophor's Avatar
    Join Date
    Jul 2009
    Location
    Missouri, USA
    Posts
    18

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

    can anyone get a console app working using this library? I would love to see something like that, ever since i'm using SDL.NET for my client, a windows form app is pointless, and for the server i prefer a console app to save some cpu, and to not deal with invoking cross threads.

  22. #62
    Fanatic Member
    Join Date
    Mar 2008
    Posts
    519

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

    Hello jmcilhinney!
    First of all, I want to thank you for creating these classes which are extremely helpful and easy to use.

    I've been using your classes for quite some time now without problems but now I thought of trying to communicate from a website to a VB.Net application. The operation wasn't that successful though.

    Does you class have support for websites? I don't think there's any difference from the TcpClass for websites and yours class. However, every time I try to connect from the website, it results with an "Connection refused" error.

    Any ideas?

    I'm currently using PHP, I've tried the official socket methods and a TcpClass which I found online.
    Both of them returns "Connection refused" anyways...

    Help appreciated!
    //Zeelia

  23. #63

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

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

    Quote Originally Posted by Zeelia View Post
    Hello jmcilhinney!
    First of all, I want to thank you for creating these classes which are extremely helpful and easy to use.

    I've been using your classes for quite some time now without problems but now I thought of trying to communicate from a website to a VB.Net application. The operation wasn't that successful though.

    Does you class have support for websites? I don't think there's any difference from the TcpClass for websites and yours class. However, every time I try to connect from the website, it results with an "Connection refused" error.

    Any ideas?

    I'm currently using PHP, I've tried the official socket methods and a TcpClass which I found online.
    Both of them returns "Connection refused" anyways...

    Help appreciated!
    //Zeelia
    It sounds like there's an issue with the way you're trying to connect, not with the classes you're trying to use to connect.

  24. #64
    Fanatic Member
    Join Date
    Mar 2008
    Posts
    519

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

    Hi! Thanks for the quick reply.

    I don't know where the problem lies since I'm trying to connect just as I am in VB.Net.
    The VB.Net application is able to connect but the PHP one can't...

    Here's how I'm trying to connect in PHP:
    Code:
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    socket_connect($socket, $host, $port);
    These lines would equivalent to the lines I'm using in VB.Net:
    Code:
            Client = New MessageClient(txtIP.Text, CInt(txtPort.Text))
            Client.Connect()
    Any ideas?

    It seems like the PHP version requires the server socket to accept the connection since there is a method in PHP called socket_accept() which the servers use.
    I haven't read through your entire code but I think that your code accepts automatically, right?

    *EDIT* I might also be trying to connect to the wrong IP address. Currently I'm trying to connect to 127.0.0.1 but now I remembered that the file lies on a webhost. So I tried to connect to my external IP but it says that it can't find the host

    *EDIT** The error was caused by the webhost which only has some specific ports open (which I didn't know)
    Last edited by Zeelia; Feb 25th, 2010 at 07:31 PM.

  25. #65
    New Member
    Join Date
    Mar 2010
    Posts
    2

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

    Hi,

    I am trying to do client application, which would be connected to multiple servers. Can you help me how to run each connection in a different thread? And how to pass different address to the new instance (Private WithEvents client As New MessageClient(hostName, remotePort))?
    So that application will be like your demo client, but I would like to start a new instance in the new thread, not in the new form.
    Appreciated the example in the code.

  26. #66

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

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

    Quote Originally Posted by zzyzx View Post
    Hi,

    I am trying to do client application, which would be connected to multiple servers. Can you help me how to run each connection in a different thread? And how to pass different address to the new instance (Private WithEvents client As New MessageClient(hostName, remotePort))?
    So that application will be like your demo client, but I would like to start a new instance in the new thread, not in the new form.
    Appreciated the example in the code.
    The whole point of my code is that you simply create the objects, tell them to connect and then tell them to communicate. Any multi-threading is handled internally, so if you want multiple clients then you simply create multiple clients. If you want to pass them different addresses then that's what you do. If you know how to pass one address to one MessageClient object then you know how to pass multiple addresses to multiple objects: it's simply doing the one thing multiple times.

  27. #67
    New Member
    Join Date
    Mar 2010
    Posts
    2

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

    Quote Originally Posted by jmcilhinney View Post
    The whole point of my code is that you simply create the objects, tell them to connect and then tell them to communicate. Any multi-threading is handled internally, so if you want multiple clients then you simply create multiple clients. If you want to pass them different addresses then that's what you do. If you know how to pass one address to one MessageClient object then you know how to pass multiple addresses to multiple objects: it's simply doing the one thing multiple times.
    Probably I need to learn a lot about object programming . I try to create a service that will communicate with various hardware modules and write data in database. I'm electronic hobbyst, not the proffessional programmers, so maybe you can help me with following code .
    Code:
    Imports Wunnell.Net
    Public Class Form1
        Private ReadOnly host As String = "localhost"
        Private ReadOnly port As Integer = 8081
        Private WithEvents client As New MessageClient(host, port)
    
        Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
            Me.client.Dispose()
        End Sub
        Private Sub connectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles connectButton.Click
            'Me.connectButton.Enabled = False
    
            'Connect to the server.
            'Me.client.Connect()
        End Sub
    
        Private Sub sendButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sendButton.Click
            Dim message = Me.messageTextBox.Text
            Me.client.Send(message)
            Me.UpdateLog(String.Format("Message (=>{0}:{1}): {2}", Me.host, Me.port, message))
            Me.messageTextBox.SelectAll()
            Me.messageTextBox.Select()
        End Sub
    
        Private Sub PromptToReconnect(ByVal message As String, ByVal caption As String, ByVal icon As MessageBoxIcon)
            Me.sendButton.Enabled = False
            Me.connectButton.Enabled = True
    
            Select Case MessageBox.Show(message, _
                                        caption, _
                                        MessageBoxButtons.YesNoCancel, _
                                        icon)
                Case Windows.Forms.DialogResult.Yes
                    'Try again to connect.
                    Me.connectButton.PerformClick()
                Case Windows.Forms.DialogResult.No
                    'Do nothing.
                Case Windows.Forms.DialogResult.Cancel
                    Me.Close()
            End Select
        End Sub
    
        Private Sub UpdateLog(ByVal text As String)
            Me.logTextBox.AppendText(text & ControlChars.NewLine)
        End Sub
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            client.Connect()
            AddHandler client.ConnectionAccepted, AddressOf Accepted
            AddHandler client.MessageReceived, AddressOf MessageRecieved
            AddHandler client.ConnectionFailed, AddressOf failed
            AddHandler client.ConnectionClosed, AddressOf cclosed
        End Sub
    
        Private Sub MessageRecieved(ByVal Sender As Object, ByVal e As MessageReceivedEventArgs)
            Me.UpdateLog(String.Format("Message ({0}=>): {1}", e.Host, e.Message))
        End Sub
        Private Sub failed(ByVal Sender As Object, ByVal e As MessageReceivedEventArgs)
            Me.PromptToReconnect("The specified server could not be found.  Would you like to try again?", _
                         "Connection Failed", _
                         MessageBoxIcon.Error)
        End Sub
        Private Sub cclosed(ByVal Sender As Object, ByVal e As MessageReceivedEventArgs)
            Me.PromptToReconnect("The connection was closed by the server.  Would you like to reconnect?", _
                                         "Connection Closed", _
                                         MessageBoxIcon.Warning)
        End Sub
        Private Sub Accepted(ByVal Sender As Object, ByVal e As ConnectionEventArgs)
            Dim host = e.Host.ToString()
            Me.Text = String.Format("{0}=>{1}", Me.client.LocalPort, host)
            Me.UpdateLog("Info: Connection accepted to " & host)
            Me.sendButton.Enabled = True
        End Sub
    End Class
    As you can see I put all code on an form and this is the end of my programming knowledge . Now I need a little help on how to dynamically create objects (clients) which would be connected to different servers.

  28. #68
    New Member
    Join Date
    Jul 2010
    Posts
    8

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

    Hi jmcilhinney,

    Im trying to implement a client server. The server is a Windows Service and the client is a Winforms application. However, the service and client keeps crashing on the following code:

    Protected Overridable Sub OnConnectionAccepted(ByVal e As ConnectionEventArgs)
    Me._synchronisingContext.Post(AddressOf RaiseConnectionAccepted, e)
    End Sub

    I have read bits and pieces on the synchronizationcontext but don't completely understand it. How would you recommend i fix the code to work. Will i need the old version before you used the synchronisatiocontext or is there a configuration i need to set for it to run under a windows service..?

    Help would greatly be appreciated!

    Thanks

  29. #69

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

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

    A crash is an unhandled exception. An exception has an error message, provided as an aid to diagnosing and fixing the problem.

  30. #70
    New Member
    Join Date
    Jul 2010
    Posts
    8

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

    Considering this code works on a GUI and not as a service i thought it would be a problem with using the synchronizationcontext which is why i didn't provide the exception. Sorry about that.

    The code i posted is throwing this error when wrapped in a try catch block:

    Sytem.NullReferenceException {"Object reference not set to an instance of an object."}

    It was captured in MessageClientServerBase.vb

    Is there any other part of the exception you need..?

    The only thing i can think of is that because there is no UI thread in a windows service, this is causing the problem but yeah im unsure of how to resolve it.

  31. #71

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

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

    Quote Originally Posted by Johno2518 View Post
    Considering this code works on a GUI and not as a service i thought it would be a problem with using the synchronizationcontext which is why i didn't provide the exception. Sorry about that.

    The code i posted is throwing this error when wrapped in a try catch block:

    Sytem.NullReferenceException {"Object reference not set to an instance of an object."}

    It was captured in MessageClientServerBase.vb

    Is there any other part of the exception you need..?

    The only thing i can think of is that because there is no UI thread in a windows service, this is causing the problem but yeah im unsure of how to resolve it.
    If it's working in a WinForms app and not in a service then it is likely that the issue is related to that fact, but it's certainly not definite. Also, the fact that it's a service specifically means that you CAN'T use the ISynchronizeInvoke interface, because there are no controls to call Invoke on.

    The thing is, the reason you need to use either the ISynchronizeInvoke interface or the SynchronizationContext class in a WinForms app is that you can only access your UI controls on the UI thread. In a Windows service there is no UI, so there's no reason to have to marshal your method call(s) to a specific thread. Basically, you don't need either. You can do whatever you want on whatever thread you happen to be on at the time. You just have to make sure that different threads don't interfere with each other's data.

  32. #72
    New Member
    Join Date
    Jul 2010
    Posts
    8

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

    So what do i change the synchronizationcontext to..? Instead should i just be raising the relevant event..?

  33. #73

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

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

    Quote Originally Posted by Johno2518 View Post
    So what do i change the synchronizationcontext to..? Instead should i just be raising the relevant event..?
    You shouldn't be changing it to anything. You should be getting rid of it because, as I said, you don't need it. Wherever the Send or Post methods of the SynchronizationContext were used, you just call the delegated method directly, e.g. where you had this:
    vb.net Code:
    1. mySynchronizationContext.Send(AddressOf SomeMethod)
    you would replace it with this:
    vb.net Code:
    1. SomeMethod()

  34. #74
    New Member
    Join Date
    Jul 2010
    Posts
    8

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

    Ok, i'll give it a go.

    Thanks for the information.

    Just one more quick question. In the GUI, it raises events in the server. Will this work in a windows service. So if i change it to as you described of calling the method directly, will it still raise events..?

  35. #75
    New Member
    Join Date
    Jul 2010
    Posts
    8

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

    Thanks for the help. It still raises events, so thats good. I have changed the code to this:


    Code:
      ''' <summary>
        ''' Raises the <see cref="ConnectionAccepted" /> event.
        ''' </summary>
        ''' <param name="e">
        ''' Contains the data for the event.
        ''' </param>
        ''' <remarks>
        ''' The event will be raised on the thread on which the current instance was created.
        ''' </remarks>
        Protected Overridable Sub OnConnectionAccepted(ByVal e As ConnectionEventArgs)
            Try
                Me._synchronisingContext.Post(AddressOf RaiseConnectionAccepted, e)
            Catch Ex As Exception
                RaiseConnectionAccepted(e)
            End Try
        End Sub
    
        ''' <summary>
        ''' Raises the <see cref="ConnectionClosed" /> event.
        ''' </summary>
        ''' <param name="e">
        ''' Contains the data for the event.
        ''' </param>
        ''' <remarks>
        ''' The event will be raised on the thread on which the current instance was created.
        ''' </remarks>
        Protected Overridable Sub OnConnectionClosed(ByVal e As ConnectionEventArgs)
            Try
                Me._synchronisingContext.Post(AddressOf RaiseConnectionClosed, e)
            Catch Ex As Exception
                RaiseConnectionClosed(e)
            End Try
        End Sub
    
        ''' <summary>
        ''' Raises the <see cref="MessageReceived" /> event.
        ''' </summary>
        ''' <param name="e">
        ''' Contains the data for the event.
        ''' </param>
        ''' <remarks>
        ''' The event will be raised on the thread on which the current instance was created.
        ''' </remarks>
        Protected Overridable Sub OnMessageReceived(ByVal e As MessageReceivedEventArgs)
            Try
                Me._synchronisingContext.Post(AddressOf RaiseMessageReceived, e)
            Catch Ex As Exception
                RaiseMessageReceived(e)
            End Try
        End Sub
    The reason is this code needs to be portable for clients and servers that may run in a service or winforms application. I know its not that ellegant, but it tries to use the standard code (for winforms) and if it fails because its running as a service it uses the other code to raise the event.

    If there is a better way of detecting what kind of thread is being run, please let me know. At the moment this works and is all i need for the time being but would appreciate some detection code sample (if any exists).

    Thanks again!

  36. #76

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

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

    Quote Originally Posted by Johno2518 View Post
    The reason is this code needs to be portable for clients and servers that may run in a service or winforms application. I know its not that ellegant, but it tries to use the standard code (for winforms) and if it fails because its running as a service it uses the other code to raise the event.

    If there is a better way of detecting what kind of thread is being run, please let me know. At the moment this works and is all i need for the time being but would appreciate some detection code sample (if any exists).

    Thanks again!
    I do wish that people would provide the whole story up-front. If you're trying to write code that can handle two different situations then that's going to be different to code that handles just the first situation and different again to code that handles just the second situation. If you want a solution then we need to know what problem we're solving. If you only provide half the relevant information then you're unlikely to get a working solution. Keep that in mind when posting in future.

    Anyway, you said originally that you got a NullReferenceException. That is presumably because Me._synchronisingContext is Nothing, which is presumably the case because SynchronizingContext.Current returns Nothing when not in either a WinForms or WPF application. As is always the case, you shouldn't try to do something and then clean up when it fails if it would be simple to check whether the action is valid beforehand. In this case, that check is indeed very simple:
    vb.net Code:
    1. If Me._synchronisingContext Is Nothing Then
    2.     'No synchronisation required.
    3.     RaiseConnectionAccepted(e)
    4. Else
    5.     'Marshal a call to the main thread.
    6.     Me._synchronisingContext.Post(AddressOf RaiseConnectionAccepted, e)
    7. End If

  37. #77
    New Member
    Join Date
    Jul 2010
    Posts
    8

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

    Originally i only wanted it to work for a service, but i then thought more about the typical usage of the DLL which could comprise of both.

    I changed my mind on how i was going to use the library. Your last reply makes sense.

    My solution was just a quick one to see if it resolved the situation for the time being.

    Thanks for the help. Greatly appreciated

  38. #78
    New Member
    Join Date
    Sep 2010
    Posts
    1

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

    I was sent to this thread by a user on the MS Forumns site. The project makes absolutely no sense to me what so ever. I've migrated over from VB6 and have been nearly tearing my hair out trying to build a simple Client/Server app but it just won't work! Then I saw this solution from the guy who suggested it and it made me even more angry because I don't understand it at all. OK I'm very new to vb.net and refuse to go "back to school" as I've hear the phrase used before. When I read the sample code it didnt have anything in there about how to accept the connection from the client or how to put the received message/text into a simple text box, absolutely nothing! I'm sorry but I HATE people that produce what they call easy to use solutions that are as complicated as hell to use!

    Erm hello, a tutorial might be nice instead of a project that yeah works but doesnt show how to do any of the things I want to do, simply or simplicity is what im looking for NOT complicated. I'm sorry but I don't understand properties, methods etc... that well in Vb.net. Why can't someone just come up with a simple solution to the problem that doesn't include 101 references here and there and everywhere!

    Client: One text box, one button ("Send"), one button ("Connect") :-
    Click Connect, Write in the text box "Hello world", Click Send = Job Done!
    Simple code to do this please!

    Server: One text box
    Sub Routine to accept connection, process message/text received :-
    Message Received and processed : Put into the text box = Job Done!
    Simple code to do this please!

    Someone for pittys sake work with me on this, I have a major problem and stress out very very easily and become angry very quickly (its called a brain defect - not enough of a chemical allowing me to retain control of myself - rather like ADHD), my apologies for any offence but can't help it.

    Dave.
    Last edited by Hack; Sep 18th, 2010 at 06:59 AM.

  39. #79
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

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

    First off, the solution posted here is simple...very simple. In fact, given the task, and the language, I'm not sure how you could write the code to do it any more simply. This is NOT complicated, providing you have some experience in VB.NET.

    However, there may be a couple of reasons why you think it is complicated.

    Reasons such as...
    Quote Originally Posted by darkdemon28
    OK I'm very new to VB.net
    And
    Quote Originally Posted by darkdemon28
    I'm sorry but I don't understand properties, methods etc... that well in Vb.net.
    At this point in your VB.NET career I would venture to say that, given those two things, nearly everything will be complicated for you. It will continue to be complicated for you until you have the one thing you don't have now, and that is experience.

    Second, I don't care about your medical conditions and I don't care about your emotional state. What I do care about is your attitude and that needs to be addressed if you wish to continue be a member in good standing on this web site.

  40. #80
    New Member
    Join Date
    Oct 2010
    Posts
    2

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

    Quote Originally Posted by jmcilhinney View Post
    There was no problem per se. The way I was doing it originally, i.e. with a SynchronisingObject property, is the same as some classes in the Framework do it. One advantage of this is that it gives you the choice of leaving the SynchronisingObject property empty and having events raised on a thread pool thread or setting it and having events raised on a specific thread. I didn't really see a reason why you specifically want my classes to raise their events on thread pool threads though, so the change I made did three things for me:

    1. It meant that a caller could completely ignore the fact that there was multi-threading involved and, in fact, wouldn't even know it from the interface. All interaction with an instance of one of my classes would occur on the same thread without any indication that any other threads were involved. There was no need for the caller to go to the (admittedly tiny) effort of setting the SynchronisingObject property to get synchronous events.

    2. It made my code a bit cleaner.

    3. It gave me a chance to play with the SynchronizationContext class, which I haven't had the pleasure of previously.

    Like I said, there was nothing actually wrong with the old implementation. If you're interested in doing something similar but aren't 100% sure how then I'm happy to provide the old code. That said, you might also be interested in using the SynchronizationContext class as the new code does.
    can you provide me with the old source plz? i would like to see the difference.
    thankyou before.

Page 2 of 7 FirstFirst 12345 ... 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