Page 4 of 7 FirstFirst 1234567 LastLast
Results 121 to 160 of 273

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

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

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

    Quote Originally Posted by chris128 View Post
    Nice to see that it wasnt just me that had to ignore the ObjectDisposed exception when calling EndAcceptTcpClient. Same for the IOException when calling EndRead.
    I assumed there was a better way to handle this that I just couldnt figure out but seeing you do the same thing makes me feel a bit better about it
    Quote Originally Posted by jmcilhinney View Post
    Yeah, I was hunting and hunting for some property that I could test before calling EndWhatever but I couldn't find anything, so I can only assume that catching the exceptions is the only way to go.
    You two might be interested in this: VS 2010 [RESOLVED] Checking for an error before it happens [TcpListener]

    I've also taken a look at the IOException that you are seeing when you call EndRead on a disposed client stream. Looks like this occurs when the internal Socket is null. You could run this check against the stream:
    Code:
    Imports System.Reflection
    Imports System.Net.Sockets
    
    ''' <summary>
    ''' Provides various Tcp related functions.
    ''' </summary>
    Public NotInheritable Class TcpUtilities
    
        '//fields
        Private Shared ReadOnly SocketPropertyInfo As PropertyInfo
    
        '//constructors
        Shared Sub New()
            TcpUtilities.SocketPropertyInfo = GetType(NetworkStream).GetProperty("Socket", _
                                                      BindingFlags.NonPublic Or _
                                                      BindingFlags.Instance)
        End Sub
    
        Private Sub New()
        End Sub
    
        '//functions
        ''' <summary>
        ''' Determines whether you can safely call <see cref="NetworkStream.EndRead">EndRead</see> 
        ''' on a <see cref="NetworkStream">NetworkStream</see> object.
        ''' </summary>
        ''' <param name="stream">
        ''' The <see cref="NetworkStream">NetworkStream</see>
        ''' to test.
        ''' </param>
        Public Shared Function CanEndRead(ByVal stream As NetworkStream) As Boolean
            If stream IsNot Nothing Then
                Dim value = TcpUtilities.SocketPropertyInfo.GetValue(stream, Nothing)
                Return value IsNot Nothing
            End If
            Return False
        End Function
    
    End Class
    I realize it utilities Reflection, but it really shouldn't be that slow.

  2. #122
    New Member
    Join Date
    Aug 2011
    Posts
    1

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

    Thank you jmcilhinney! I have been searching for a way to add tcp communication to one of my applications for over a week and happened upon this example. It worked perfectly right out of the box. My only tweak was to send serialized objects instead of free form text. This project saved me a lot of time!

    As a side note, even though it wasn't the intended purpose, this project is also a great example of how to use inheritance in a real world situation.

    Thanks again!

  3. #123
    New Member
    Join Date
    Jan 2012
    Location
    Antioch, CA
    Posts
    3

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

    Hi. Newbie here.

    I would like to try and write a program in VB 2010 that queries and receives data to/from a technical instrument (an RF spectrum analyzer). The analyzer requires that the ASCII codes STX (0x02 - start of text) and ETX (0x03 - end of text) be sent to it before and after each query (example - Chr(STX) & "frequency?" & Chr(ETX) ). The analyzer only accepts the standard 128 character ASCII table.

    I believe that I read that jmcilhinney's Wunnell code converts everything to binary before sending, because it expects the server to translate it back (so as to accommodate unicode characters).

    Can anybody tell me what lines need to be changed in order to send and receive standard ASCII?
    Last edited by sherrel; Jan 11th, 2012 at 11:53 PM.

  4. #124

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

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

    Quote Originally Posted by sherrel View Post
    I believe that I read that jmcilhinney's Wunnell code converts everything to binary before sending, because it expects the server to translate it back (so as to accommodate unicode characters).

    Can anybody tell me what lines need to be changed in order to send and receive standard ASCII?
    It's not to accommodate Unicode characters. It's because bytes are the only thing you can transmit. Any data that you want to transmit must be converted to a Byte array It's then up to the server to interpret those bytes in the appropriate way. In your case, you just need to make sure that you use an ASCIIEncoding object to convert your text to Bytes, i.e. use System.Text.Encoding.ASCII.GetBytes(). I'm not sure whether that's what I do in the code here but, if not, the only difference would the actual encoding object. All the rest would be the same.

  5. #125
    New Member
    Join Date
    Jan 2012
    Location
    Antioch, CA
    Posts
    3

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

    OK. I think I see in the client transmit code where I would change Dim buffer As Byte() = Me.Encoding.GetBytes(message) to Dim buffer As Byte() = System.Text.Encoding.ASCII.GetBytes(message) in the MessageClient.vb file; is that not correct?

    But I don't seem to be able to locate where I would change the decoding for the client receive in order to receive ASCII from the spectrum analyzer instead of binary. Or am I completely misunderstanding things?

    FYI. My project will be to send a series of 12 standard queries to the analyzer (such as frequency?, bandwidth?, reference level?, etc.), and to receive back 11 answers, and the response to the 12th query will consist of about 4000 bytes representing the data points of the trace displayed on the analyzer screen. I will stuff all this into a .CSV file for later analysis by another pre-written program.
    Last edited by sherrel; Jan 12th, 2012 at 05:15 AM.

  6. #126

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

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

    In that code of mine, Me.Encoding is an Encoding object. If you simply assign System.Text.Encoding.ASCII to that property then you don't have to change my code at all.

    As for receiving data, there would be a corresponding call to the GetString method of an Encoding object. You simply use an ASCIIEncoding object read, just as you did to write.

  7. #127
    Hyperactive Member ibennz's Avatar
    Join Date
    Aug 2010
    Posts
    282

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

    Very nice work !!! but could you help me how set my ip address to allow two pc (not on lan) to connect on it. I tried ip forward unsuccesfully . looked for NaT . Didn't understood . My ip is already static. Is there a way to do it via codes on vb2008?

  8. #128

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

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

    Quote Originally Posted by ibennz View Post
    Is there a way to do it via codes on vb2008?
    No. It's a router issue and well beyond the scope of this thread.

  9. #129
    Hyperactive Member ibennz's Avatar
    Join Date
    Aug 2010
    Posts
    282

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

    I need a little help with :
    Private WithEvents server As New MessageServer(port)

    How to make the listner listen on a specific IP adress? since user IP wont be forwarded , i wanted also them to use the server form.

  10. #130

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

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

    Quote Originally Posted by ibennz View Post
    How to make the listner listen on a specific IP adress?
    If you're asking that question then you haven't actually read the code. I don't have the time, or the inclination, to explain every little detail to everyone. That's why I provided copious comments throughout the code. Read them.

  11. #131
    Hyperactive Member ibennz's Avatar
    Join Date
    Aug 2010
    Posts
    282

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

    The thing is I read all ur code.. I changed this :

    Code:
        Public Sub New()
        
            Me.Initialise(IPAddress.Any, 0)
        End Sub
    To this :
    Code:
       Public Sub New()
            Dim ExtIp As IPAddress = IPAddress.Parse("_external ip")
    
            Me.Initialise(ExtIp, 3000)
        End Sub
    The server form still doesnt work on other pc . I changed down some others setting that was related to server IP/Port and the application just crashed. So If you dont mind, I would need your help. Thanks in advance.

  12. #132

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

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

    Quote Originally Posted by ibennz View Post
    The thing is I read all ur code.. I changed this :

    Code:
        Public Sub New()
        
            Me.Initialise(IPAddress.Any, 0)
        End Sub
    To this :
    Code:
       Public Sub New()
            Dim ExtIp As IPAddress = IPAddress.Parse("_external ip")
    
            Me.Initialise(ExtIp, 3000)
        End Sub
    The server form still doesnt work on other pc . I changed down some others setting that was related to server IP/Port and the application just crashed. So If you dont mind, I would need your help. Thanks in advance.
    You obviously didn't read it properly because the MessageServer has multiple constructors and at least one of them, I believe more than one, allow you to specify an IP address. You don't have to change any code in the MessageServer class at all. You simply have to create the MessageServer instance with the appropriate constructor.

  13. #133
    Hyperactive Member ibennz's Avatar
    Join Date
    Aug 2010
    Posts
    282

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

    I tried that already :

    Code:
     Private WithEvents server As New MessageServer("External_ip")
    event that:
    Code:
     Private WithEvents server As New MessageServer("External_ip:Port")
    Application crash. Any clue ?

  14. #134

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

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

    Quote Originally Posted by ibennz View Post
    I tried that already :

    Code:
     Private WithEvents server As New MessageServer("External_ip")
    event that:
    Code:
     Private WithEvents server As New MessageServer("External_ip:Port")
    Application crash. Any clue ?
    I must have missed where you mentioned that you'd already tried that. I must also have missed where you provided information about the exception that occurred. If I seem a bit miffed it's because I am. I'm more than happy to help with legitimate issues but all this back and forth because you're not reading information already providing and you're not providing information required to diagnose the issue is a big waste of my time. I shouldn't have to ask for an error message.

  15. #135
    Hyperactive Member ibennz's Avatar
    Join Date
    Aug 2010
    Posts
    282

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

    Im using my external ip .(forwarded) I tried with local ip (127.0.0.1) and worked . Also with my internal IP4 Address(only on current pc , when i send it to friend . Doesn't ). Any clue?

    Code:
    System.InvalidOperationException was unhandled
      Message="An  error; is produced during the creation of the form. For more information, consult Exception.InnerException.  error is: The required address is not valid in its context"
      Source="testoi"
      StackTrace:
           &#224; testoi.My.MyProject.MyForms.Create__Instance__[T](T Instance) dans 17d14f5c-a337-4978-8281-53493378c1071.vb:ligne 190
           &#224; testoi.My.MyProject.MyForms.get_Form1()
           &#224; testoi.My.MyApplication.OnCreateMainForm() dans C:\Users\user\AppData\Local\Temporary Projects\testoi\My Project\Application.Designer.vb:ligne 35
           &#224; Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
           &#224; Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
           &#224; Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
           &#224; testoi.My.MyApplication.Main(String[] Args) dans 17d14f5c-a337-4978-8281-53493378c1071.vb:ligne 81
           &#224; System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           &#224; Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           &#224; System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           &#224; System.Threading.ThreadHelper.ThreadStart()
      InnerException: System.Net.Sockets.SocketException
           Message="The required address is not valid in its context"
           Source="System"
           ErrorCode=10049
           NativeErrorCode=10049
           StackTrace:
                &#224; System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
                &#224; System.Net.Sockets.Socket.Bind(EndPoint localEP)
                &#224; System.Net.Sockets.TcpListener.Start(Int32 backlog)
                &#224; Wunnell.Net.MessageServer.Initialise(IPAddress ipAddress, Int32 port)
                &#224; Wunnell.Net.MessageServer..ctor(String address, Int32 port)
                &#224; testoi.Form1..ctor() dans C:\Users\user\AppData\Local\Temporary Projects\testoi\Form1.vb:ligne 4
           InnerException:
    Last edited by ibennz; Feb 1st, 2012 at 08:51 PM. Reason: Traduction / Additional info

  16. #136
    New Member
    Join Date
    Feb 2012
    Posts
    2

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

    I am completely new to vb. When I try to run this I am getting the following message:

    "a project with an Ouput Type of Class Library cannot be started directly. In order to debug this project, add an executable project to this solution which references the library project. Set the executable project as the startup project."

    I have no idea what this means or how to do this. When I click under Client Test and try to run in debug mode I get this message. What should I do?

  17. #137

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

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

    Quote Originally Posted by lastly View Post
    I am completely new to vb. When I try to run this I am getting the following message:

    "a project with an Ouput Type of Class Library cannot be started directly. In order to debug this project, add an executable project to this solution which references the library project. Set the executable project as the startup project."

    I have no idea what this means or how to do this. When I click under Client Test and try to run in debug mode I get this message. What should I do?
    You've got the wrong project selected as the startup project for the solution. In the Solution Explorer, right-click the appropriate project and select it as the startup project.

    I have to say though, if you don't know that then the concepts demonstrated by this solution will almost certainly be a mystery to you. Maybe you should get a good grasp of the basics and start with simpler things before trying to tackle this sort of thing.

  18. #138
    Hyperactive Member ibennz's Avatar
    Join Date
    Aug 2010
    Posts
    282

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

    @ jmcilhinney well I heard you cant listen on other ip than these avaible on the machine. So I guess tcp communication is useless If you dont forward the ip/port on the pc you are actually using. Ive also tried to figure if there was a way to open a port and send the message ignoring about the fact the ip isnt forwarded or static . Doesn't worked. Also trying to look if there is a way to forward or create a temporary IP to allow communication , But no success . So if you have any tips , I would appreciated. Looked also on socket side and winsock , both are almost the same than .net tcpListner. Looked UDP , same and API isnt what i was looking for. FTP have too much issues and it doesnt keep direct connection like TCP. If there is any other type of communication also that is similar to TCP , I would appreciate few links . Thanks in advance.

    And if you know about this :

    Code:
    Re: Access Visual Studio Development Server from other pc
    Jun 22, 2009 03:46 PM|LINK
    
    Hi, I understand this issue has been closed for a while but will post this here for the sake of anyone else looking for an answer. If you want to connect to your development server from a remote box you can do it my redirecting the request through a proxy on your local machine. Using something like MSSoapT does the trick nicely and it also allows you to see the SOAP or whatever content you are sending or receiving. Hope this helps someone!
    Last edited by ibennz; Feb 4th, 2012 at 07:01 PM. Reason: Additional Information

  19. #139
    Hyperactive Member ibennz's Avatar
    Join Date
    Aug 2010
    Posts
    282

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

    Which kind of encoding you are using ? When I try to send data from anyother client it doesn't decode it correctly .

    Code:
    Try
                    Dim str As String = Me.Text
                    Dim sw As IO.StreamWriter
                    Try
                        sw = New IO.StreamWriter(client.GetStream)
                        sw.Write(str)
                        sw.Flush()
                    Catch ex As Exception
    
                    End Try
                Catch ex As Exception
    
                End Try
    I was able to decode the sent info of your server to my client by trying the encode methode. But I dont know how encode text and sent it in the right format to allow your server to read it . There is the code I used to read the previous information sent to my client.

    Code:
     Private Sub DoRead(ByVal ar As System.IAsyncResult)
          
            Dim totalRead As Integer
            Try
                totalRead = client.GetStream.EndRead(ar) 'Ends the reading and returns the number of bytes read.
            Catch ex As Exception
                'The underlying socket have probably been closed OR an error has occured whilst trying to access it, either way, this is where you should remove close all eventuall connections            'to this client and remove it from the list of connected clients.
            End Try
            If totalRead > 0 Then
                'the readBuffer array will contain everything read from the client
                Dim receivedString As String = System.Text.Encoding.Unicode.GetString(readBuffer, 0, totalRead)
                MessageReceived(receivedString)
            End If
            Try
                client.GetStream.BeginRead(readBuffer, 0, BYTES_TO_READ, AddressOf DoRead, Nothing) 'Begin the reading again.
            Catch ex As Exception
                'The underlying socket have probably been closed OR an error has occured whilst trying to access it, either way, this is where you should remove close all eventuall connections                'to this client and remove it from the list of connected clients.
            End Try
        End Sub
    Last edited by ibennz; Feb 5th, 2012 at 10:19 AM. Reason: More Info

  20. #140
    Hyperactive Member ibennz's Avatar
    Join Date
    Aug 2010
    Posts
    282

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

    Found out . Encode text as byte then as ASCII:

    Code:
    Dim byt As Byte() = System.Text.Encoding.Unicode.GetBytes(Me.Text)
                    Dim str As String = System.Text.Encoding.ASCII.GetString(byt)

  21. #141
    New Member
    Join Date
    Feb 2012
    Posts
    7

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

    Let me start by saying thanks! This is excellent stuff. It saved me a lot of time writing my own way of communicating over LAN.
    I have one problem though which I can't quite figure out why is happening.

    When i close the connection (shut down any client) the server automatically shuts down too. There isn't any error, it just ends.

    I work in VS2010. Let me point out that everything else is working properly on both end and that I've used the exact examples as those in the Message Client-Server project. The only difference is that I didn't use MDI form for the client.

    Btw, one interesting remark. When I run client minimized, and close him by right clicking on the taskbar and choosing close window, then everything works fine - the Closed connection event is raised on the server side, and most importantly, it continues to run.

    Every suggestion would be valuable since I have no clue what to do next.

  22. #142
    New Member
    Join Date
    Feb 2012
    Posts
    7

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

    Whenever I close any client the server shuts down -> unhandled exception. I tried everything I could think of but without result so far...


    System.IO.IOException was unhandled
    Message=Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
    Source=System
    StackTrace:
    at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
    at Wunnell.Net.MessageServer.Read(IAsyncResult ar)
    at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
    at System.Net.ContextAwareResult.CompleteCallback(Object state)
    at System.Threading.ExecutionContext.runTryCode(Object userData)
    at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    at System.Net.ContextAwareResult.Complete(IntPtr userToken)
    at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
    at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
    at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
    InnerException: System.Net.Sockets.SocketException
    Message=An existing connection was forcibly closed by the remote host
    Source=System
    ErrorCode=10054
    NativeErrorCode=10054
    StackTrace:
    at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
    at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
    InnerException:

  23. #143

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

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

    You will see in my code that there are a few places that I am handling and swallowing exceptions that occur due to asynchronous operations in progress when connections are closed. It sounds like this might be another that you would have to add an exception handler for.

  24. #144
    New Member
    Join Date
    Feb 2012
    Posts
    7

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

    Thx, I'll try that.

    Another thing. When you shut down the server, the client detects that and the ConnectionClosed event occurs, along with the prompt to reconnect. But if you start the server again and choose on the client side to try to reconnect, it doesn't work. Any ideas why?
    Last edited by OBijac; Mar 1st, 2012 at 05:01 PM.

  25. #145
    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

    Doesn't appear to work when started in a thread that isn't the initial application thread ... as SynchronizationContext.Current returns nothing in this case

    Is there a way around this? As I am making a plugin for an application that is closed source and i do not have access to the application thread .

    Thanks Kris

  26. #146

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

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

    SychronizationContex.Current will always return a value no matter what thread your on IF you are in a Windows Forms or WPF application. The point of invoking a method on a specific thread is to be able to access a control directly. Outside of WinForms and WPF there are no controls so there's no need to invoke a method on a specific thread.

    If you were in one of those types of apps then the only way that you would not be able to use SynchronizationContext successfully is if the application created the instance of your type in a secondary thread in the first place. If the application developer wants to do that then you simply raise your event or whatever on whatever thread you're on and it's then the app's responsibilty to invoke back to the UI thread.

  27. #147

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

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

    Quote Originally Posted by OBijac View Post
    Thx, I'll try that.

    Another thing. When you shut down the server, the client detects that and the ConnectionClosed event occurs, along with the prompt to reconnect. But if you start the server again and choose on the client side to try to reconnect, it doesn't work. Any ideas why?
    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.

  28. #148
    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

    Quote Originally Posted by jmcilhinney View Post
    SychronizationContex.Current will always return a value no matter what thread your on IF you are in a Windows Forms or WPF application. The point of invoking a method on a specific thread is to be able to access a control directly. Outside of WinForms and WPF there are no controls so there's no need to invoke a method on a specific thread.

    If you were in one of those types of apps then the only way that you would not be able to use SynchronizationContext successfully is if the application created the instance of your type in a secondary thread in the first place. If the application developer wants to do that then you simply raise your event or whatever on whatever thread you're on and it's then the app's responsibilty to invoke back to the UI thread.
    It is a console application, and i do not have access to the source code of it ... does this mean this method isn't possible?

    Thanks
    Kris

  29. #149
    New Member
    Join Date
    Feb 2012
    Posts
    7

    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.
    That has crossed my mind. Is there a way to set the clients port #, rather than randomizing it? (I presume it works that way since it's always different and I couldn't find any variables that points to that)

  30. #150
    Hyperactive Member
    Join Date
    Apr 2010
    Posts
    402

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

    This looks lie an example of what I am looking for. the only problem is that when I download it, and load it into VB.net 2010 express, upon pressing F5 to run, it generates an error
    'A Project With an Output type of class library can not be started directly' In order to debug, as an executable project to this solution which references the library project. Set the executable project as the startup project.

    This does not make any scene to me
    Last edited by Signalman; Mar 6th, 2012 at 04:56 PM.

  31. #151

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

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

    Quote Originally Posted by Signalman View Post
    This looks lie an example of what I am looking for. the only problem is that when I download it, and load it into VB.net 2010 express, upon pressing F5 to run, it generates an error
    'A Project With an Output type of class library can not be started directly' In order to debug, as an executable project to this solution which references the library project. Set the executable project as the startup project.

    This does not make any scene to me
    That's because you haven't set the startup project of the solution properly. The IDE has probably selected the first project by default or whatever project you currently have open. You need to explicitly select the application project as the startup project, not a library project.

  32. #152
    Hyperactive Member
    Join Date
    Apr 2010
    Posts
    402

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

    thanks, that's got it working. All I have got to do is work out how the prog works & incorporate it into my project.

  33. #153
    New Member
    Join Date
    Feb 2012
    Posts
    7

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

    Quote Originally Posted by jmcilhinney View Post
    You will see in my code that there are a few places that I am handling and swallowing exceptions that occur due to asynchronous operations in progress when connections are closed. It sounds like this might be another that you would have to add an exception handler for.
    Tried catching exceptions everywhere and without luck.

    I returned to your original example project and the same thing happened there too. I use VS2010 (.net 4) and convert your project with 0 errors so I guess it should work.

    Once again, the issue is this. When connected, if you terminate the client for any reason (for example, manually end the client process), the server crashes and reports the following: An unhandled exception ("System.IO.IOException") occured in Wunnell.MessageServerTest.exe [5580].

    I'm a newb when it comes to writing this type of applications, but I have a hunch this has to do with disposing the client. If the client simply ends - the server crashes, but if I do a "Me.client.Dispose()" before it ends - everything checks out fine. The problem is, when the client process ends (and it could happen for various reasons) I'm unable to dispose the client because your ClientWindow_FormClosed event never occurs...

    If this makes any sense to you, please help

  34. #154
    New Member
    Join Date
    Feb 2012
    Location
    Brisbane, Australia
    Posts
    3

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

    Removed
    Last edited by scorpydude; Mar 14th, 2012 at 09:08 PM.

  35. #155
    New Member
    Join Date
    Feb 2012
    Posts
    7

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

    Any idea what to do next?

  36. #156

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

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

    If there's an unhandled exception then you can handle the exception. You're obviously not doing it in the right place or else you're trying to catch the wrong type of exception.

  37. #157
    New Member
    Join Date
    Feb 2012
    Location
    Brisbane, Australia
    Posts
    3

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

    removed
    Last edited by scorpydude; Mar 14th, 2012 at 09:08 PM.

  38. #158
    New Member
    Join Date
    Feb 2012
    Posts
    7

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

    Quote Originally Posted by jmcilhinney View Post
    If there's an unhandled exception then you can handle the exception. You're obviously not doing it in the right place or else you're trying to catch the wrong type of exception.
    When you're right - you're right! I was doing it the wrong way.
    Thank you very much for the help. One thing still puzzles me. Could you tell me, how could I set the port # of the Client's local end of the connection?

    You see, if the Client's connection with the Server is lost, and restored back again, the prompt to reconnect won't work.
    As you wrote earlier, this is probably because the port # changes.
    Quote Originally Posted by jmcilhinney
    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.

  39. #159
    New Member
    Join Date
    May 2012
    Posts
    1

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

    Hi ¡

    i've used this library and works fine¡ thanks¡

    but, i've found a possible issue, the initial SEQuence number at the establishment of a TCP socket seems random, with numbers like 237927293, where it must be 0, is this a problem of an uninitialized variable? thanks for all.

  40. #160
    Addicted Member
    Join Date
    Jan 2007
    Posts
    199

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

    Hi! jmcilhinney Thank you for sample code. I'm getting tired of searching the web about asynchronous socket and found your sample project so basically this what I need. I have modified your code how it disconnect and connect on my application. I'm using listview ipaddress is save as listview tag while port is subitems the port is changing every now and so I can't save it to my database. Now My issue is sending message to client on your sample you used combox, my question is how can I make dirertcast work on me as I used listview tag and subitems. is there a work around for it? Below is the code I have on sending message. Also one more question on your client how does it handle when client gets' power off or network cable was accidentally unplug.

    Code:
        Private Sub SendMessageToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles SendMessageToolStripMenuItem.Click
            Dim message As String = InputBox("Enter your message to selected terminal", "Message")
    
            If message = String.Empty Then
                Exit Sub
            Else
                For Each checkedItems As ListViewItem In Me.lv_main.SelectedItems
                    Dim host = DirectCast(checkedItems.Tag & ":" & checkedItems.SubItems(18).Text, HostInfo)
    
                    'Send the message to the selected client.
                    Me.server.Send(host, message)
                Next
            End If
        End Sub

Page 4 of 7 FirstFirst 1234567 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