-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Quote:
Originally Posted by
chris128
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
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.
-
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!
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Hi. Newbie here. :confused:
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?
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Quote:
Originally Posted by
sherrel
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.
-
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? :confused:
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.
-
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.
-
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?
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Quote:
Originally Posted by
ibennz
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.
-
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.
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Quote:
Originally Posted by
ibennz
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.
-
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.
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Quote:
Originally Posted by
ibennz
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.
-
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 ?
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Quote:
Originally Posted by
ibennz
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.
-
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:
à testoi.My.MyProject.MyForms.Create__Instance__[T](T Instance) dans 17d14f5c-a337-4978-8281-53493378c1071.vb:ligne 190
à testoi.My.MyProject.MyForms.get_Form1()
à testoi.My.MyApplication.OnCreateMainForm() dans C:\Users\user\AppData\Local\Temporary Projects\testoi\My Project\Application.Designer.vb:ligne 35
à Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
à Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
à Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
à testoi.My.MyApplication.Main(String[] Args) dans 17d14f5c-a337-4978-8281-53493378c1071.vb:ligne 81
à System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
à 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:
à System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
à System.Net.Sockets.Socket.Bind(EndPoint localEP)
à System.Net.Sockets.TcpListener.Start(Int32 backlog)
à Wunnell.Net.MessageServer.Initialise(IPAddress ipAddress, Int32 port)
à Wunnell.Net.MessageServer..ctor(String address, Int32 port)
à testoi.Form1..ctor() dans C:\Users\user\AppData\Local\Temporary Projects\testoi\Form1.vb:ligne 4
InnerException:
-
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?
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Quote:
Originally Posted by
lastly
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.
-
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!
-
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
-
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)
-
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. :confused: 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.
-
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:
-
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.
-
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?
-
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
-
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.
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Quote:
Originally Posted by
OBijac
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.
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Quote:
Originally Posted by
jmcilhinney
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
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
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.
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)
-
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 :sick:
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Quote:
Originally Posted by
Signalman
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 :sick:
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.
-
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. :wave::wave::wave:
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Quote:
Originally Posted by
jmcilhinney
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 :)
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Any idea what to do next?
-
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.
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Quote:
Originally Posted by
jmcilhinney
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.
-
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.:)
-
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
-
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
-
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.
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Quote:
Originally Posted by
tokneneng
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.
-
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:
Private Sub tmr_idle_Tick(sender As System.Object, e As System.EventArgs) Handles tmr_idle.Tick
If tsl_idle.Text = "Disconnected" Or tsl_idle.Text = "Connection was closed by the server." Then
'Me.Dispose()
Me.client.Connect()
tmr_idle.Enabled = False
Else
If tsl_idle.Text = "Connected" Then
tmr_idle.Enabled = False
Exit Sub
End If
End If
End Sub
When server back on client does not connect again.
-
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?
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
Quote:
Originally Posted by
jmcilhinney
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.
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
hi jmcilhinney can you gave idea how to fix it? thanks
-
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.
-
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:
For Each item In FileIO.FileSystem.GetFiles("C:\TestImages",FileIO.SearchOption.SearchTopLevelOnly,"*.jpg")
Me.client.Send(New Bitmap(item))
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
-
Re: [VB2008/.NET 3.5] Asynchronous TcpListener & TcpClient
@i00, I'm afraid I don't know.
-
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.
-
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
-
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
-
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.
-
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.
-
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!
-
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.
-
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:
Dim match = myList.FirstOrDefault(Function(o) o.Name = name)
If match <> Nothing Then
-
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?
-
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.