Results 1 to 37 of 37

Thread: [2005] UDP socket client example?

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    [2005] UDP socket client example?

    I need an example for a UDP socket client. Haven't been able to find a relevant one anywhere. I'd like the example to use the System.Net.Sockets.UDPClient control, and be asynchronous, when it comes to receiving data.

  2. #2
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] UDP socket client example?

    There is a thread on this forum that shows that. I'd post one myself, but I haven't actually tested it yet, so it probably doesn't work yet. Maybe tomorrow, but I borrowed much of it from a thread here.
    My usual boring signature: Nothing

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?

    I can't seem to find that thread. Can you provide me with a link?

  4. #4
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] UDP socket client example?

    This thread is particularly interesting:

    http://www.vbforums.com/showthread.p...ight=UDPClient

    I found the same thing, you can't receive with UDPClient, and have to use a socket instead. I was just looking at my code, and found that I had implemented that. Still looking for the post I mentioned, though.

    Here's another interesting point:

    http://www.vbforums.com/showthread.p...ight=UDPClient


    Ok, this is the thread I was talking about:

    http://www.vbforums.com/showthread.p...ight=UDPClient
    My usual boring signature: Nothing

  5. #5
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] UDP socket client example?

    Looks like UDP is a perpetual problem. I should be diving into it tomorrow, as my code is about ready to be tested. Should be interesting, since most everybody is having one problem or another with it.
    My usual boring signature: Nothing

  6. #6

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?

    I am so glad you take it that way! I hope this will somehow lead to a solution.

  7. #7
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] UDP socket client example?

    Wouldnt this work? I have no ability to test it since I have nowhere to connect the udp client.

    VB Code:
    1. Private uClient As Net.Sockets.UdpClient
    2.     Private thrRead As Threading.Thread
    3.  
    4.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    5.         uClient = New Net.Sockets.UdpClient("host", 0)
    6.         thrRead = New Threading.Thread(AddressOf DoRead)
    7.         thrRead.Start()
    8.     End Sub
    9.  
    10.     Private Sub DoRead()
    11.         Dim byteArray(uClient.Client.ReceiveBufferSize) As Byte
    12.         Do
    13.             uClient.Client.Receive(byteArray, uClient.Client.ReceiveBufferSize, Net.Sockets.SocketFlags.None)
    14.             MessageBox.Show(System.Text.Encoding.Default.GetString(byteArray))
    15.         Loop
    16.     End Sub

    the uClient.Client.Recieve() method is not asynchronous, so it will block the current thread until it recieves something.
    Last edited by Atheist; Jul 7th, 2007 at 06:39 PM.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  8. #8

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?

    I will try that tomorrow, and report if it worked. Thank you.

  9. #9
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] UDP socket client example?

    According to the first link I provided, UDPClient.Receive is buggy, and won't work.
    My usual boring signature: Nothing

  10. #10
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] UDP socket client example?

    Quote Originally Posted by Shaggy Hiker
    According to the first link I provided, UDPClient.Receive is buggy, and won't work.
    Yeah but does that also apply to the Recieve method of the underlying socket? Im calling UDPClient.Client.Recieve (UDPClient.Client references to the underlying socket), dont know if that works better/worse.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  11. #11

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?

    You guys are cool. I can't believe you're actually doing all this just for me. VBForums for the wind!

  12. #12
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] UDP socket client example?

    Quote Originally Posted by Atheist
    Yeah but does that also apply to the Recieve method of the underlying socket? Im calling UDPClient.Client.Recieve (UDPClient.Client references to the underlying socket), dont know if that works better/worse.
    Sorry, I missed that point. You are right, that should work. I'm trying that route myself.
    My usual boring signature: Nothing

  13. #13

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?

    And about sending things? Does that work? And can you provide me with an example? Also, did anyone figure out if Atheist's code would work? I can't try it myself before monday.

  14. #14
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] UDP socket client example?

    Ok, I tested my program, and it works...so far. Sending and receiving is fine, but I still have one issue with delegates to work out since the messages come in on one thread. Here's the whole class, minus some stuff that is specific to this application:

    vb Code:
    1. Public Class UDPControl
    2.     Implements IDisposable
    3.  
    4.  
    5.     'The UDP listening components.
    6.     Private WithEvents locUDPIn As System.Net.Sockets.Socket
    7.     Private WithEvents locUDPOut As System.Net.Sockets.UdpClient
    8.     Private WithEvents myTimer As System.Windows.Forms.Timer
    9.     Private ThreadListen As New Threading.Thread(AddressOf WaitForPending)
    10.     Private timeCount As Integer
    11.  
    12.     'A few endpoints.
    13.     Private mRobot As System.Net.IPEndPoint
    14.     Private mRegistered As Boolean
    15.     Private mIAsynch As IAsyncResult
    16.  
    17.     'The dataQueue
    18.     Private dgList As Queue(Of DataGramReceiver)
    19.  
    20.     'The result
    21.     Private callType As Integer
    22.     Private disposedValue As Boolean = False        ' To detect redundant calls
    23.  
    24.     Public Shared TheUDP As New UDPControl 'The only instance of the Singleton class.
    25.  
    26. #Region "Constructors and Destructors"
    27.  
    28.     Private Sub New()
    29.         'Set up the queue.
    30.         dgList = New Queue(Of DataGramReceiver)
    31.         locUDPIn = New Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Dgram, Net.Sockets.ProtocolType.Udp)
    32.         locUDPOut = New System.Net.Sockets.UdpClient(11012)
    33.         locUDPIn.Bind((New Net.IPEndPoint(Net.IPAddress.Any, 11011)))
    34.         locUDPOut.EnableBroadcast = True
    35.  
    36.         callType = 0
    37.         myTimer = New System.Windows.Forms.Timer
    38.         myTimer.Interval = 1000
    39.         myTimer.Enabled = False
    40.  
    41.         'Start listening.
    42.         ThreadListen.Name = "Listening Thread"
    43.         ThreadListen.Start()
    44.     End Sub
    45.  
    46.     ' IDisposable
    47.     Protected Overridable Sub Dispose(ByVal disposing As Boolean)
    48.         If Not Me.disposedValue Then
    49.             If disposing Then
    50.                 locUDPOut.Close()
    51.                 myTimer.Dispose()
    52.                 ThreadListen.Abort()
    53.                 locUDPIn.Close()
    54.             End If
    55.  
    56.             ' TODO: free shared unmanaged resources
    57.         End If
    58.         Me.disposedValue = True
    59.     End Sub
    60.  
    61. #Region " IDisposable Support "
    62.     ' This code added by Visual Basic to correctly implement the disposable pattern.
    63.     Public Sub Dispose() Implements IDisposable.Dispose
    64.         ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
    65.         Dispose(True)
    66.         GC.SuppressFinalize(Me)
    67.     End Sub
    68. #End Region
    69.  
    70. #End Region
    71.  
    72. #Region "Properties and Events"
    73.  
    74.     Public Event DataReceived(ByVal senType As Integer)
    75.  
    76.     Public Event ReceiveFailed()
    77.  
    78.     Private Event DataIn()
    79.    
    80. #End Region
    81.  
    82. #Region "Public Functions"
    83.  
    84.     Public Sub CallSynchTime()
    85.         Dim buff(0) As Byte
    86.         Dim broad As New System.Net.IPEndPoint(System.Net.IPAddress.Broadcast, 11012)
    87.  
    88.         buff(0) = 100 'Nothing but a single byte.
    89.  
    90.         locUDPOut.Send(buff, 1, broad)
    91.     End Sub
    92.    
    93. #End Region
    94.  
    95. #Region "Private Functions"
    96.  
    97.     Private Sub WaitForPending()
    98.         Dim bHolder(99) As Byte
    99.         Dim numIn As Integer
    100.         Dim dgRec As DataGramReceiver
    101.         Dim bTrans() As Byte
    102.  
    103.         While True
    104.             If CBool(locUDPIn.Available) Then
    105.                 numIn = locUDPIn.Receive(bHolder, 100, Net.Sockets.SocketFlags.None)
    106.                 If numIn > 4 Then
    107.                     If bHolder(0) = 128 Then
    108.                         'Set the holder up to the right size.
    109.                         ReDim bTrans(numIn - 3)
    110.                         Array.Copy(bHolder, 2, bTrans, 0, numIn - 2)
    111.                         dgRec = New DataGramReceiver(bHolder(3), bTrans)
    112.                         Add(dgRec)
    113.                     ElseIf bHolder(0) = 100 Then
    114.                         ReDim bTrans(numIn - 2)
    115.                         Array.Copy(bHolder, 1, bTrans, 0, numIn - 2)
    116.                         dgRec = New DataGramReceiver(100, bTrans)
    117.                         Add(dgRec)
    118.                     End If
    119.                 End If
    120.             End If
    121.         End While
    122.     End Sub
    123.  
    124.     'Adds one DGR to the queue
    125.     Private Sub Add(ByVal dgR As DataGramReceiver)
    126.         'Set the monitor.
    127.         Threading.Monitor.Enter(Me)
    128.         Try
    129.             dgList.Enqueue(dgR) 'That's all that happens.
    130.         Finally
    131.             Threading.Monitor.Exit(Me)
    132.         End Try
    133.  
    134.     End Sub
    135.  
    136. #End Region
    137.  
    138. End Class

    I stripped out much of the code for specific messages. What I tested was that on computer 1 I had this code running, and called SynchTime. On computer 2 I had a similar class that returned the time on system 2. When I called SynchTime on System 1, the message was received on System 2, which sent back the time. The time is preceeded by the value 100, so if you look in the WaitForPending function, you will see where the first value in the byte array is used to do different things. This is just in there so that I can sort the incoming messages, and it is largely irrelevant to UDP.

    One issue I have not yet resolved is that messages come in on the listening thread. You will see the Private Function Add, which uses a Monitor to get ahold of a Queue, and add an item to it. The main thread will then have to get items off the Queue. I can do this via polling, but I want to have the one thread raise an event on the other, and I haven't got that working yet.
    My usual boring signature: Nothing

  15. #15
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] UDP socket client example?

    Oh yeah, I should also note that I am using two different sockets. This program is not truly bi-directional, as all remote systems will be sending to one central receiver, which will be broadcasting to all listeners. I was somewhat concerned that there might be too much traffic on one line, so I am using one port as Input, and another port as Output. Each need only listen to one, and talk on the other. I have no idea whether or not this is a superior solution, but none of the client systems will ever need to listen on the same line they will be talking on, and many may NEVER need to listen on the talking port (they will be downstream only nodes). Meanwhile, the Server (brainstem in this case, since it is a robot) will ONLY listen to the listening line, as it will NEVER have to make a request to any of the other systems.
    My usual boring signature: Nothing

  16. #16

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?

    Quote Originally Posted by Shaggy Hiker
    Ok, I tested my program, and it works...so far. Sending and receiving is fine, but I still have one issue with delegates to work out since the messages come in on one thread. Here's the whole class, minus some stuff that is specific to this application:

    vb Code:
    1. Public Class UDPControl
    2.     Implements IDisposable
    3.  
    4.  
    5.     'The UDP listening components.
    6.     Private WithEvents locUDPIn As System.Net.Sockets.Socket
    7.     Private WithEvents locUDPOut As System.Net.Sockets.UdpClient
    8.     Private WithEvents myTimer As System.Windows.Forms.Timer
    9.     Private ThreadListen As New Threading.Thread(AddressOf WaitForPending)
    10.     Private timeCount As Integer
    11.  
    12.     'A few endpoints.
    13.     Private mRobot As System.Net.IPEndPoint
    14.     Private mRegistered As Boolean
    15.     Private mIAsynch As IAsyncResult
    16.  
    17.     'The dataQueue
    18.     Private dgList As Queue(Of DataGramReceiver)
    19.  
    20.     'The result
    21.     Private callType As Integer
    22.     Private disposedValue As Boolean = False        ' To detect redundant calls
    23.  
    24.     Public Shared TheUDP As New UDPControl 'The only instance of the Singleton class.
    25.  
    26. #Region "Constructors and Destructors"
    27.  
    28.     Private Sub New()
    29.         'Set up the queue.
    30.         dgList = New Queue(Of DataGramReceiver)
    31.         locUDPIn = New Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Dgram, Net.Sockets.ProtocolType.Udp)
    32.         locUDPOut = New System.Net.Sockets.UdpClient(11012)
    33.         locUDPIn.Bind((New Net.IPEndPoint(Net.IPAddress.Any, 11011)))
    34.         locUDPOut.EnableBroadcast = True
    35.  
    36.         callType = 0
    37.         myTimer = New System.Windows.Forms.Timer
    38.         myTimer.Interval = 1000
    39.         myTimer.Enabled = False
    40.  
    41.         'Start listening.
    42.         ThreadListen.Name = "Listening Thread"
    43.         ThreadListen.Start()
    44.     End Sub
    45.  
    46.     ' IDisposable
    47.     Protected Overridable Sub Dispose(ByVal disposing As Boolean)
    48.         If Not Me.disposedValue Then
    49.             If disposing Then
    50.                 locUDPOut.Close()
    51.                 myTimer.Dispose()
    52.                 ThreadListen.Abort()
    53.                 locUDPIn.Close()
    54.             End If
    55.  
    56.             ' TODO: free shared unmanaged resources
    57.         End If
    58.         Me.disposedValue = True
    59.     End Sub
    60.  
    61. #Region " IDisposable Support "
    62.     ' This code added by Visual Basic to correctly implement the disposable pattern.
    63.     Public Sub Dispose() Implements IDisposable.Dispose
    64.         ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
    65.         Dispose(True)
    66.         GC.SuppressFinalize(Me)
    67.     End Sub
    68. #End Region
    69.  
    70. #End Region
    71.  
    72. #Region "Properties and Events"
    73.  
    74.     Public Event DataReceived(ByVal senType As Integer)
    75.  
    76.     Public Event ReceiveFailed()
    77.  
    78.     Private Event DataIn()
    79.    
    80. #End Region
    81.  
    82. #Region "Public Functions"
    83.  
    84.     Public Sub CallSynchTime()
    85.         Dim buff(0) As Byte
    86.         Dim broad As New System.Net.IPEndPoint(System.Net.IPAddress.Broadcast, 11012)
    87.  
    88.         buff(0) = 100 'Nothing but a single byte.
    89.  
    90.         locUDPOut.Send(buff, 1, broad)
    91.     End Sub
    92.    
    93. #End Region
    94.  
    95. #Region "Private Functions"
    96.  
    97.     Private Sub WaitForPending()
    98.         Dim bHolder(99) As Byte
    99.         Dim numIn As Integer
    100.         Dim dgRec As DataGramReceiver
    101.         Dim bTrans() As Byte
    102.  
    103.         While True
    104.             If CBool(locUDPIn.Available) Then
    105.                 numIn = locUDPIn.Receive(bHolder, 100, Net.Sockets.SocketFlags.None)
    106.                 If numIn > 4 Then
    107.                     If bHolder(0) = 128 Then
    108.                         'Set the holder up to the right size.
    109.                         ReDim bTrans(numIn - 3)
    110.                         Array.Copy(bHolder, 2, bTrans, 0, numIn - 2)
    111.                         dgRec = New DataGramReceiver(bHolder(3), bTrans)
    112.                         Add(dgRec)
    113.                     ElseIf bHolder(0) = 100 Then
    114.                         ReDim bTrans(numIn - 2)
    115.                         Array.Copy(bHolder, 1, bTrans, 0, numIn - 2)
    116.                         dgRec = New DataGramReceiver(100, bTrans)
    117.                         Add(dgRec)
    118.                     End If
    119.                 End If
    120.             End If
    121.         End While
    122.     End Sub
    123.  
    124.     'Adds one DGR to the queue
    125.     Private Sub Add(ByVal dgR As DataGramReceiver)
    126.         'Set the monitor.
    127.         Threading.Monitor.Enter(Me)
    128.         Try
    129.             dgList.Enqueue(dgR) 'That's all that happens.
    130.         Finally
    131.             Threading.Monitor.Exit(Me)
    132.         End Try
    133.  
    134.     End Sub
    135.  
    136. #End Region
    137.  
    138. End Class

    I stripped out much of the code for specific messages. What I tested was that on computer 1 I had this code running, and called SynchTime. On computer 2 I had a similar class that returned the time on system 2. When I called SynchTime on System 1, the message was received on System 2, which sent back the time. The time is preceeded by the value 100, so if you look in the WaitForPending function, you will see where the first value in the byte array is used to do different things. This is just in there so that I can sort the incoming messages, and it is largely irrelevant to UDP.

    One issue I have not yet resolved is that messages come in on the listening thread. You will see the Private Function Add, which uses a Monitor to get ahold of a Queue, and add an item to it. The main thread will then have to get items off the Queue. I can do this via polling, but I want to have the one thread raise an event on the other, and I haven't got that working yet.
    Uuuuh thank you so much for that! Thanks! Really appreciated! However, can you try to make it standalone, so it won't support multiple clients, and not support server? I only need a client, that needs to be able to send and receive data.

  17. #17
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] UDP socket client example?

    What's the difference between what I have and that? UDP is never really a server, this is just a variation where one port is listened to, and a different port is written to. You could use this exact same code if you change the port numbers to be the same. The UDPClient won't Read correctly (a bug exists, as noted in one of the earlier threads), so I had to use a socket for the receiving, while I still used the UDPClient to send data. I connected them to two different ports, but you could just as easily use the same port number (I use 11011 and 11012) for both, and it would work the same. One object would read, and a different object would write, but if it was on the same port, it should be fine.
    My usual boring signature: Nothing

  18. #18

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?

    I know, but I'd like it more simply. I need to learn something as well, you know... And well, your code is extremely useful, but yet, very hard to understand. I am not that good at programming yet. If you can make it kind of like the one Atheist made, that would be awesome!

  19. #19
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] UDP socket client example?

    So why not use what Atheist provided? They are essentially the same thing in that a thread is started that reads from the UDPClient. I'm not sure what difference there is. Sending via a UDP is much easier than reading, which is why it is such a tiny piece of my code. All you do is make up a byte array with the bytes you want to send, and call the UDPClient.Send() method. What you put in that byte array is a whole different question, and not related to UDP.
    My usual boring signature: Nothing

  20. #20

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?


  21. #21
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] UDP socket client example?

    I don't undertstand your point. Atheist posted simpler code, I posted a more complicated and thorough example. There was an intermediate version in the third link I provided back in post#4. Are none of these suitable for your situation, and why not?
    My usual boring signature: Nothing

  22. #22

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?

    The client only needs to be able to receive and send data. Also, I don't want it to be able to be a server.

  23. #23
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] UDP socket client example?

    That's what Atheists code does. There's no simpler solution, which presents some issues that he didn't address. The issues are these:

    1) To send, you would just use the UDPClient.Send method, but that sends an array of bytes. Since you rarely will actually work with an array of bytes, there is some manipulation required to take whatever you want to send, and turn it into an array of bytes. If all you are sending is a string, that's not very hard: System.Text.Encoding.ASCII.GetBytes() should be the method (I didn't look it up, but it would be really close).

    2) The other issue related to sending is whether or not you want to broadcast, or send to a specific IP endpoint. In my example, I used broadcast, which I frankly think is easier, but in my case I HAD to use broadcast because of the program design. The problem with sending to a specific IP address is that you have to know the address, which you may or may not.

    3) The issue with receiving data is only that receiving pretty much has to happen on a separate thread, as Atheist and I both have. The reason for this is that receiving occurs in a tight, perpetual, loop. If you receive in your main thread, it will block until something is received, though you could set it up so that it just listens for a second or two, then goes on, but this would mean you would miss messages. Therefore, a thread for receiving is pretty nearly the ONLY way you will ever see that implemented. The problem with a thread is that you then have to deal with getting information back to the main thread. Atheists code solved that by never sending information out of the thread (he just posted it in a messagebox). If you want to display it in a control in the UI thread, you can use Invoke or BeginInvoke on the control. If you just want to raise an event in the main thread, I have a way to do that, and it's simple, but I'll let you decide what you want to do.
    My usual boring signature: Nothing

  24. #24

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?

    Quote Originally Posted by Atheist
    Wouldnt this work? I have no ability to test it since I have nowhere to connect the udp client.

    VB Code:
    1. Private uClient As Net.Sockets.UdpClient
    2.     Private thrRead As Threading.Thread
    3.  
    4.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    5.         uClient = New Net.Sockets.UdpClient("host", 0)
    6.         thrRead = New Threading.Thread(AddressOf DoRead)
    7.         thrRead.Start()
    8.     End Sub
    9.  
    10.     Private Sub DoRead()
    11.         Dim byteArray(uClient.Client.ReceiveBufferSize) As Byte
    12.         Do
    13.             uClient.Client.Receive(byteArray, uClient.Client.ReceiveBufferSize, Net.Sockets.SocketFlags.None)
    14.             MessageBox.Show(System.Text.Encoding.Default.GetString(byteArray))
    15.         Loop
    16.     End Sub

    the uClient.Client.Recieve() method is not asynchronous, so it will block the current thread until it recieves something.
    This works, but how to send data as simple as this too? Good job Atheist.

  25. #25
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] UDP socket client example?

    Sending is even easier:

    vb Code:
    1. Public Sub SendString(st1 as string)        
    2.  Dim buff() As Byte        
    3.  Dim broad As New System.Net.IPEndPoint(System.Net.IPAddress.Broadcast, 11012)        
    4.  buff() = system.text.encoding.ASCII.GetBytes(st1)        
    5.  UClient.Send(buff, 1, broad)    
    6. End Sub

    where 11012 is the port number, which is something you can decide on. Use whatever you like, but a bunch of the low numbers are reserved, and there's an upper limit, though I forget what it is.
    My usual boring signature: Nothing

  26. #26

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?

    I just corrected your code! So full of mistakes? You mean something like this?

    Public Sub Send(ByVal Data As String)
    Dim Buffer() As Byte
    Dim Broad As New System.Net.IPEndPoint(System.Net.IPAddress.Broadcast, 4898)
    Buffer = System.Text.Encoding.ASCII.GetBytes(Data)
    Client.Send(Buffer, Buffer.Length, Broad)
    End Sub

  27. #27

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?

    Even the one I corrected doesn't work. Atheist, any solution for this?

  28. #28

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?

    Or maybe it's actually the DoRead sub that doesn't work? I can't tell!

    vb Code:
    1. Private Sub DoRead(ByVal Port As Integer)
    2.             Dim ByteArray(Client.Client.ReceiveBufferSize) As Byte
    3.             Do
    4.                 Client.Client.Receive(byteArray, Client.Client.ReceiveBufferSize, Net.Sockets.SocketFlags.None)
    5.                 RaiseEvent ClientReceived(System.Text.Encoding.Default.GetString(ByteArray))
    6.             Loop
    7.         End Sub
    8.         Public Sub Send(ByVal Data As String)
    9.             Dim Buffer() As Byte
    10.             Buffer = System.Text.Encoding.ASCII.GetBytes(Data)
    11.             Client.Send(Buffer, Buffer.Length)
    12.         End Sub

    Should they both work?

  29. #29
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] UDP socket client example?

    You'd have to show more code, you've made sufficient changes to the code Atheist originally posted that the actual source of the problem you are having cannot be determined. Perhaps you have the ports set wrong, perhaps you are trying to raise an event on a background thread and expecting something good to happen in a different thread.

    But since you have gotten downright rude at this point, I might as well step out.
    My usual boring signature: Nothing

  30. #30

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?

    Quote Originally Posted by Shaggy Hiker
    You'd have to show more code, you've made sufficient changes to the code Atheist originally posted that the actual source of the problem you are having cannot be determined. Perhaps you have the ports set wrong, perhaps you are trying to raise an event on a background thread and expecting something good to happen in a different thread.

    But since you have gotten downright rude at this point, I might as well step out.
    Okay. I hereby show my whole class.

    vb Code:
    1. Public Class Client
    2.         Private Client As Net.Sockets.UdpClient
    3.         Public Event ClientReceived(ByVal Data As String)
    4.         Public Event ClientError(ByVal Number As Long, ByVal Description As String)
    5.         Public Event ServerConnected()
    6.         Public ReadOnly Property Socket() As Net.Sockets.UdpClient
    7.             Get
    8.                 Return Client
    9.             End Get
    10.         End Property
    11.         Public Sub Connect(ByVal HostName As String, ByVal Port As Integer)
    12.             If Port = 0 Then
    13.                 Err.Raise(44, "MathyProductions.Sockets.TCP.Client", "The port to connect to was not set")
    14.             End If
    15.             If HostName = vbNullString Then
    16.                 Err.Raise(45, "MathyProductions.Sockets.TCP.Client", "The hostname to connect to was not set")
    17.             End If
    18.             Client = New Net.Sockets.UdpClient(HostName, Port)
    19.             DoRead
    20.         End Sub
    21.         Private Sub DoRead()
    22.             Dim ByteArray(Client.Client.ReceiveBufferSize) As Byte
    23.             Do
    24.                 Client.Client.Receive(byteArray, Client.Client.ReceiveBufferSize, Net.Sockets.SocketFlags.None)
    25.                 RaiseEvent ClientReceived(System.Text.Encoding.Default.GetString(ByteArray))
    26.             Loop
    27.         End Sub
    28.         Public Sub Send(ByVal Data As String)
    29.             Dim Buffer() As Byte
    30.             Buffer = System.Text.Encoding.ASCII.GetBytes(Data)
    31.             Client.Send(Buffer, Buffer.Length)
    32.         End Sub
    33.     End Class

  31. #31

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2006
    Location
    Denmark
    Posts
    291

    Re: [2005] UDP socket client example?

    Nevermind, got the code working. DoRead was not even called! *LOL*

  32. #32
    Fanatic Member MikkyThomeon's Avatar
    Join Date
    Oct 2002
    Location
    At work...
    Posts
    648

    Re: [2005] UDP socket client example?

    Hi Shaggy . . .

    I would greatly appreciate if you could post or, considering the circumstances of this thread, pm the DataGramReceiver code.

    Many Thanks
    Mike

  33. #33
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [2005] UDP socket client example?

    Should this thread be in "Network Programming"?
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  34. #34
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [2005] UDP socket client example?

    Quote Originally Posted by MikkyThomeon
    Hi Shaggy . . .

    I would greatly appreciate if you could post or, considering the circumstances of this thread, pm the DataGramReceiver code.

    Many Thanks
    Mike
    I don't have it handy, but I can add it to this thread later today or tomorrow. What is it that you are looking for, though? My datagramreceiver is somewhat custom. The first two bytes have special meaning, while the remainder of the bytes are one of a variety of structures that have been serialized to a binary stream. Of those first two bytes, one indicates the origin of the message, while the second one tells what type of message has been serialized.

    Are you looking for an example of serializing/deserializing the structures? I think I got that from something Atheist posted, but I could post the way I handle it.
    My usual boring signature: Nothing

  35. #35
    Fanatic Member MikkyThomeon's Avatar
    Join Date
    Oct 2002
    Location
    At work...
    Posts
    648

    Re: [2005] UDP socket client example?

    oops - Thanks I have figured something out to do the trick. In fact the mulit threading is not even needed - I have a barcode scanning program that uses UDP as a server to send an instruction to multiple viewer clients on the network so that the clients are updated whenever an item is scanned from one of the warehouses.

    I was initially thinking of sending the data directly to the clients but its far more reliable to save the data from teh scanning application directly to the database by odbc and then broadcast the event.

    Thanks anyway
    Mike

  36. #36
    New Member
    Join Date
    May 2008
    Posts
    13

    Re: [2005] UDP socket client example?

    When I try out the code that Shaggy Hiker made, I only get
    "DataGramReceiver' is not defined."

    What can I do about this? I really need this to work!

  37. #37
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] UDP socket client example?

    DataGramReceiver is a custom class that SH wrote himself, I'm sure he'll let you know how it works if you PM him.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

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