Section 23.7. Connectionless ClientServer Interaction with Datagrams


23.7. Connectionless Client/Server Interaction with Datagrams

So far, we have discussed connection-oriented, streams-based transmissions using the TCP protocol to ensure that the packets of data are transmitted reliably. Now we consider connectionless transmission using datagrams and UDP.

Connectionless transmission via datagrams resembles the method by which the postal service carries and delivers mail. Information is bundled and sent in packets called datagrams, which can be thought of as similar to letters sent through the mail. If a large message will not fit in one envelope, it is broken into separate message pieces and placed in separate, sequentially numbered envelopes. All the envelopes are mailed at once. They may arrive in order, out of order or not at all. The person at the receiving end reassembles the message pieces in sequential order before attempting to interpret the message. If the message is small enough to fit in one envelope, the sequencing problem is eliminated, but it is still possible that the message will never arrive. (Unlike with postal mail, duplicate datagrams could reach receiving computers.) .NET provides the UdpClient class for connectionless transmission. Like TcpListener and TcpClient, UdpClient uses methods from class Socket. UdpClient method Send transmits data with Socket's SendTo method, and UdpClient method Receive reads data with Socket's ReceiveFrom method.

The programs in Fig. 23.3 and Fig. 23.4 use datagrams to send packets of information between client and server applications. In the PacketClient application, the user types a message into a TextBox and presses Enter. The client converts the message to a Byte array and sends it to the server. The server receives the packet and displays the packet's information, then echoes, or returns, the packet to the client. When the client receives the packet, the client displays the packet's information. In this example, classes FrmPacket-Client and FrmPacketServer are implemented similarly.

Figure 23.3. Server-side portion of connectionless client/server computing.

  1  ' Fig. 23.3: FrmPacketServer.vb  2  ' Set up a server that will receive packets from a  3  ' client and send the packets back to the client.  4  Imports System.Net          5  Imports System.Net.Sockets  6  Imports System.Threading    7  8  Public Class FrmPacketServer  9     Private client As UdpClient        10     Private receivePoint As IPEndPoint 11 12     ' initialize variables and thread for receiving  packets 13     Private Sub FrmPacketServer_Load(ByVal sender As System.Object, _ 14        ByVal e As  System.EventArgs) Handles MyBase.Load 15 16        client = New UdpClient(50000)                      17        receivePoint = New IPEndPoint(New IPAddress(0), 0) 18        Dim readThread As New Thread( _                    19           New ThreadStart(AddressOf WaitForPackets))      20        readThread.Start()                                 21     End Sub ' FrmPacketServer_Load 22 23     ' shut down the server 24     Private Sub FrmPacketServer_FormClosing( _ 25        ByVal sender As System.Object, _ 26        ByVal e As  System.Windows.Forms.FormClosingEventArgs) _ 27        Handles MyBase.FormClosing 28 29        System.Environment.Exit(System.Environment.ExitCode) 30     End Sub ' FrmPacketServer_FormClosing 31 32     ' Delegate that allows method DisplayMessage to be called 33     ' in the thread that creates and maintains the GUI 34     Private Delegate Sub DisplayDelegate(ByVal  message As String) 35 36     ' method DisplayMessage sets txtDisplay's Text property 37     ' in a thread-safe manner 38     Private Sub DisplayMessage(ByVal message As String) 39        ' if modifying txtDisplay is not thread safe 40        If txtDisplay.InvokeRequired Then 41           ' use inherited method Invoke to execute DisplayMessage 42           ' via a Delegate 43           Invoke(New DisplayDelegate(AddressOf  DisplayMessage), _ 44              New Object() {message}) 45        ' OK to modify txtDisplay in current thread 46        Else 47           txtDisplay.Text &= message 48        End If 49     End Sub ' DisplayMessage 50 51     ' wait for a packet to arrive 52     Public Sub WaitForPackets() 53        While True 54           ' set up packet 55           Dim data As Byte() = client.Receive(receivePoint) 56           DisplayMessage( _ 57              vbCrLf & "Packet received:" & vbCrLf & "Length:" & _ 58              data.Length & vbCrLf & "Contents: " & _ 59              System.Text.Encoding.ASCII.GetString(data)) 60 61           ' echo information from packet back to client 62           DisplayMessage(vbCrLf & vbCrLf & "Echo data  back to client...") 63           client.Send(data, data.Length, receivePoint) 64           DisplayMessage(vbCrLf & "Packet sent" & vbCrLf) 65        End While 66     End Sub ' WaitForPackets 67  End Class ' FrmPacketServer 

Figure 23.4. Client portion of connectionless client/server computing.

   1  ' Fig. 23.4: FrmPacketClient.vb   2  ' Set up a client that sends packets to  a server and receives   3  ' packets from a server.   4  Imports System.Net           5  Imports System.Net.Sockets   6  Imports System.Threading     7   8  Public Class FrmPacketClient   9     Private client As UdpClient         10     Private receivePoint As IPEndPoint  11  12    ' initialize variables and thread for receiving packets  13     Private Sub FrmPacketClient_Load(ByVal sender As System.Object, _  14        ByVal e As System.EventArgs) Handles MyBase.Load  15  16        receivePoint = New IPEndPoint(New IPAddress(0), 0)                   17        client = New UdpClient(50001)                                        18        Dim thread As New Thread(New ThreadStart(AddressOf WaitForPackets))  19        thread.Start()                                                       20     End Sub ' FrmPacketClient_Load  21 22      ' shut down the client 23      Private Sub FrmPacketClient_FormClosing( _ 24         ByVal sender As System.Object, _ 25         ByVal e As System.Windows.Forms.FormClosingEventArgs) _ 26         Handles MyBase.FormClosing 27 28         System.Environment.Exit(System.Environment.ExitCode) 29      End Sub ' FrmPacketClient_FormClosing 30 31      ' Delegate that allows method  DisplayMessage to be called 32      ' in the thread that creates and maintains the GUI 33      Private Delegate Sub DisplayDelegate(ByVal message As String) 34 35      ' method DisplayMessage sets txtDisplay's Text property 36      ' in a thread-safe  manner 37      Private Sub DisplayMessage(ByVal message As String) 38         ' if modifying txtDisplay is not thread safe 39         If txtDisplay.InvokeRequired Then 40            ' use inherited method Invoke to execute DisplayMessage 41            ' via a Delegate 42            Invoke(New DisplayDelegate(AddressOf DisplayMessage), _ 43               New Object() {message}) 44         ' OK to modify txtDisplay in current thread 45         Else 46           txtDisplay.Text &= message 47         End If 48      End Sub ' DisplayMessage 49 50      ' send a packet 51      Private Sub txtInput_KeyDown(ByVal sender As System.Object, _ 52         ByVal e As System.Windows.Forms.KeyEventArgs) _ 53         Handles txtInput.KeyDown 54 55         If e.KeyCode = Keys.Enter Then 56            ' create packet (datagram) as string 57            Dim packet As String = txtInput.Text 58            txtDisplay.Text &= _ 59               vbCrLf & "Sending packet containing: " & packet 60 61            ' convert packet to Byte array                                   62            Dim data As Byte() = System.Text.Encoding.ASCII.GetBytes(packet) 63 64            ' send packet to server on port 50000              65            client.Send(data, data.Length, "localhost", 50000) 66            txtDisplay.Text &= vbCrLf & "Packet sent" & vbCrLf 67            txtInput.Clear() 68         End If 69      End Sub ' txtInput_KeyDown 70 71      ' wait for packets to arrive 72      Public Sub WaitForPackets() 73         While True 74         ' receive Byte array from server                  75         Dim data As Byte() = client.Receive(receivePoint) 76 77         ' output packet data to TextBox 78         DisplayMessage( _ 79            vbCrLf & "Packet received:" & vbCrLf & "Length: " & _ 80            data.Length & vbCrLf & "Contents: " & _ 81            System.Text.Encoding.ASCII.GetString(data) & vbCrLf) 82        End While 83     End Sub ' WaitForPackets 84  End Class  ' FrmPacketClient 

(a) Packet Client window before sending a packet to the server

(b) Packet Client window after sending a packet to the server and receiving it back

FrmPacketServer Class

Figure 23.3 defines class FrmPacketServer. Line 16 in the Load event handler for class FrmPacketServer creates an instance of the UdpClient class that receives data at port number 50000. This initializes the underlying Socket for communications. Line 17 creates an instance of class IPEndPoint to hold the IP address and port number of the client(s) that transmit to FrmPacketServer. The first argument to the IPEndPoint constructor is an IPAddress object; the second argument is the port number of the endpoint. These values are both 0, because we need only instantiate an empty IPEndPoint object. The IP addresses and port numbers of clients are copied into the IPEndPoint when datagrams are received from clients.

Lines 3449 define DisplayDelegate and DisplayMessage, allowing any thread to modify txtdisplay's Text property.

FrmPacketServer method WaitForPackets (lines 5266) executes an infinite loop while waiting for data to arrive at the FrmPacketServer. When information arrives, UdpClient method Receive (line 55) receives a Byte array from the client. We pass to Receive the IPEndPoint object created in the constructorthis provides the method with an IPEndPoint to which the program copies the client's IP address and port number.

Lines 5659 display the packet's information and content in FrmPacketServer's TextBox. Line 63 echoes the data back to the client, using UdpClient method Send. This version of Send takes three argumentsthe Byte array to send, the array's length and the IPEndPoint to which to send the data. We use array data returned by method Receive as the data, the length of array data as the length and the IPEndPoint passed to method Receive as the data's destination. The IP address and port number of the client that sent the data are stored in receivePoint, so passing receivePoint to Send allows FrmPacket-Server to respond to the client.

FrmPacketClient Class

Class FrmPacketClient (Fig. 23.4) works similarly to class FrmPacketServer, except that the client sends packets only when the user types a message in a TextBox and presses the Enter key. When this occurs, the program calls event handler txtInput_KeyDown (lines 5169). Line 62 converts the String that the user entered in the TextBox to a Byte array. Line 65 calls UdpClient method Send to send the Byte array to the FrmPacketServer that is located on localhost (i.e., the same machine). We specify the port as 50000, which we know to be FrmPacketServer's port.

Lines 3348 define DisplayDelegate and DisplayMessage, allowing any thread to modify txtdisplay's Text property.

Line 17 instantiates a UdpClient object to receive packets at port 50001we choose port 50001 because the FrmPacketServer already occupies port 50000. Method WaitFor-Packets of class FrmPacketClient (lines 7283) uses an infinite loop to wait for these packets. UdpClient method Receive blocks until a packet of data is received (line 75). The blocking performed by method Receive does not prevent class FrmPacketClient from performing other services (e.g., handling user input), because a separate thread (line 18) runs method WaitForPackets.

When a packet arrives, lines 7881 display its contents in the TextBox. The user can type information in FrmPacketClient's TextBox and press the Enter key at any time, even while a packet is being received. The event handler for the TextBox processes the event and sends the data to the server.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net