Winsock, .NET and the Compact Framework

Getting started using Winsock Interface is outlined in this book excerpt from Steve Makofsky's Pocket PC Network Programming.

This Content Component encountered an error

Winsock and .NET

The System.Net.Sockets namespace provides all of the classes that are needed to communicate over the Winsock interface (see Chapter 1 for more information about general Winsock programming) when using the Compact Framework. The namespace provides the classes and enumerations described in Table 12.6.

Table 12.6 The System.Net.Sockets Namespace





Name Object Type Description
AddressFamily Enumeration Address scheme for a Socket class
AddressFamily Enumeration Address scheme for a Socket class
IrDACharacterSet Enumeration Character sets supported for infrared transfers
IrDAClient Class Handles the client in an infrared transfer
IrDADeviceInfo Class Provides information about infrared connections and servers
IrDADeviceInfo Class Provides information about infrared connections and servers
IrDAHints Enumeration Infrared device types
IrDAListener Class Handles the server in an infrared transfer
LingerOption Class Handles the socket linger options
MulticastOption Class Handles multicast address groups
NetworkStream Class Handles a stream over a network connection
ProtocolFamily Enumeration Socket protocol types that are available
ProtocolFamily Enumeration Socket protocol types that are available
ProtocolType Enumeration Socket protocol
SelectMode Enumeration Socket polling modes
Socket Class Class to handle socket communications
Socket Class Class to handle socket communications
Socket Class Class to handle socket communications
SocketException Class Exception that is used when an error occurs in a Socket class
SocketFlags Enumeration Socket constants
SocketOptionName Enumeration Socket names option constant values
SocketOptionLevel Enumeration Socket level option constant values
SocketShutdown Enumeration Socket shutdown constants
SocketType Enumeration Type of socket
TcpClient Class Class to handle TCP socket connections to a server
TcpListener Class Class to handle TCP socket connections as a server
UdpClient Class Class to handle UDP socket connections for both client and server

The namespace provides four classes that you will use primarily when working with Winsock connections:

  1. The System.Net.Sockets.Socket class is essentially a full wrapper around a traditional SOCKET handle. It provides all of the functionality for both connectionless and connection-based TCP and UDP communications.
  2. The System.Net.Sockets.TcpClient class provides all of the methods and properties for the client side of a TCP connection to a server.
  3. The System.Net.Sockets.TcpListener class provides all of the methods and properties for the server side of a TCP connection that will listen for incoming connections on a specific port.
  4. The System.Net.Sockets.UdpClient class provides all of the methods and properties for sending and receiving connectionless datagrams.

The Generic Socket Class

The System.Net.Sockets.Socket class is used to perform basic Win¬sock functionality in a manner similar to using a standard SOCKET handle. To create a new Socket object, you use the following constructor:

public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType);

All of the parameters that you use are standard enumerations that are part of the System.Net.Sockets namespace. The first parameter, addressFamily, should specify the addressing scheme for the socket, such as AddressFamily.InterNetwork for an IPv4 socket. This is followed by the type of socket you are creating, which is followed by the protocol that the socket should use.

The following example creates a standard IPv4 socket for communicating over a TCP connection using the IP protocol:

using System; 
using System.Data; 
using System.Net.Sockets; 
 namespace PocketPCNetworkProgramming {
   class SocketTestClass {
      static void Main(string[] args) {
         // Create a new socket
         System.Net.Sockets.Socket newSocket = new Socket(
           AddressFamily.InterNetwork, 
           SocketType.Stream, 
            ProtocolType.IP); 
         // Do something with the new socket
       }
   }
}

The System.Net.Sockets.Socket class supports the methods and properties described in Table 12.7.

Table 12.7 Socket Class Methods and Properties

Method Description
Accept() Creates a new System.Net.Sockets.Socket for the incoming connection
BeginAccept() Begins asynchronous Accept() operation
BeginConnect() Begins asynchronous Connect() operation
BeginReceive() Begins asynchronous Receive() operation
BeginReceiveFrom() Begins asynchronous Receive() operation from a specific remote EndPoint
BeginSend() Begins asynchronous Send() operation
BeginSendTo() Begins asynchronous Send() operation to a specific remote EndPoint
BeginSendTo() Begins asynchronous Send() operation to a specific remote EndPoint
Bind() Associates the socket with a local EndPoint
Close() Closes the socket
Connect() Establishes a connection with another host
EndAccept() Asynchronously accepts an incoming connection
EndConnect() Ends asynchronous Connect() operation
EndReceive() Ends asynchronous Receive() operation from a specific remote EndPoint
EndSend() Ends asynchronous Send() operation EndPoint
GetSocketOption() Returns the value of the socket options
IOControl() Sets low-level socket options
Listen() Sets low-level socket options

Poll() Returns the status of the socket
Receive() Returns the status of the socket
ReceiveFrom() Receives data over a socket from a specific remote EndPoint
Select() Returns the status of one or more sockets
Send() Sends data over a socket
SendTo() Sends data over a socket to a specific remote EndPoint
SendTo() Sends data over a socket to a specific remote EndPoint
SetSocketOption() Sets the value of the socket options
Shutdown() Stops communications over a socket

Property Get/Set Description
AddressFamily Get Gets the addressing scheme used for the socket
Available Get Gets the amount of data on the socket that is ready to be read
Blocking Get/set Gets or sets whether the socket is in blocking mode
Connected Get Returns TRUE if the socket is connected
Handle Get Gets the socket handle
ProtocolType Get Gets the protocol type for the socket
RemoteEndPoint e Get Gets the remote EndPoint for the socket
SocketType Get Gets the type of socket

Once you have created your Socket class, communicating over the Internet is relatively straightforward. The class supports methods such as Send() and Receive(), which are almost identical to the standard Winsock functions:

// Create a new socket
System.Net.Sockets.Socket webSocket = new  
  Socket(AddressFamily.InterNetwork, SocketType.Stream,   
 ProtocolType.IP); 
// Make a request from a Web server
// Resolve the IP address for the server, and get the //  
IPEndPoint for it on port 80
System.Net.IPHostEntry webServerHost =
   System.Net.Dns.GetHostByName("www.furrygoat.com");
System.Net.IPEndPoint webServerEndPt = new
   System.Net.IPEndPoint(webServerHost.AddressList[0], 80);
// Set up the HTTP request string to get the main index page
byte[] httpRequestBytes =
   System.Text.Encoding.ASCII.GetBytes("GET /    
HTTP/1.0rnrn");
// Connect the socket to the server
webSocket.Connect(webServerEndPt); 
// Send the request synchronously
int bytesSent = webSocket.Send(httpRequestBytes,   
httpRequestBytes.Length, SocketFlags.None);
// Get the response from the request. 
We will continue to request // 4096 bytes from the response stream 
and concat the string into // the strReponse variable
byte[] httpResponseBytes = new byte[4096];
int bytesRecv = webSocket.Receive(httpResponseBytes,   
httpResponseBytes.Length, SocketFlags.None); 
strResponse = System.Text.Encoding.ASCII.GetString  
(httpResponseBytes, 0, bytesRecv); 
while(bytesRecv > 0) {
   bytesRecv = webSocket.Receive(httpResponseBytes,    
httpResponseBytes.Length, SocketFlags.None); 
   strResponse = strResponse +       
System.Text.Encoding.ASCII.GetString(
      httpResponseBytes, 0, bytesRecv); 
}
// At this point, the strResponse string has the Web page. // Do something with it
// ...
// Clean up the socket
webSocket.Shutdown(SocketShutdown.Both);
webSocket.Close();

Although using the Socket class provides you with a robust set of methods to handle almost any type of connection, you are more likely to use one of the more specific connection classes, such as TcpClient or TcpListener, to handle your protocol-specific network commu¬nications.

TCP Connections

As described in Chapter 1, a TCP (or streaming) socket provides you with an error-free data pipe (between a client and server) that is used to send and receive data over a communications session. The format of the data sent over the connection is typically up to you, but several ¬well-known Internet protocols, such as HTTP and FTP, use this type of connection.

The .NET Compact Framework provides you with two separate classes that can be used to handle TCP communications. The System.Net.Sockets.TcpListener class is used to create a socket that can accept an incoming connection request. This is also known as a server.

To create a TCP client, you use the System.Net.Sockets.TcpClient class. The methods provide functionality to connect to a server that is listening on a specific port.

TCP Servers

To create a new TcpListener object, you can use one of the following constructors:

public TcpListener(int port);
public TcpListener(IPAddress localaddr, int port);
public TcpListener(IPEndPoint localEP); 

All three constructors basically do the same thing. The first one needs only the port number on which you want the object to listen. The second requires an IPAddress class that represents the local IP address of the device, and is followed by the port. The final constructor takes an IPEndPoint class, which should represent the local IP address and port on which to listen.

The following example shows how you can use each one of the constructors to initialize a new TcpListener class:

// Method 1 - Listen on the local IP address, port 80.
System.Net.Sockets.TcpListener tcpServerSocket = new   
TcpListener(80);
// Method 2 - Listen on the local IP address, port 80.
System.Net.IPAddress localIPAddr =   
System.Net.IPAddress.Parse("127.0.0.1");
System.Net.Sockets.TcpListener tcpServerSocket2 = new   
TcpListener(localIPAddr, 80);
// Method 3 - Listen on the local IP address by creating an // endpoint
System.Net.IPEndPoint localIpEndPoint = new   
System.Net.IPEndPoint(localIPAddr, 80);
System.Net.Sockets.TcpListener tcpServerSocket3 = new
   TcpListener(localIpEndPoint); 

The TcpListener object provides the methods and property described in Table 12.8.

Table 12.8 TCPListener Class Methods and Properties

Method Description
AcceptSocket() Accepts an incoming TCP connection request and returns a Socket class
AcceptTcpClient() Accepts an incoming TCP connection request and returns a TcpClient class
Pending( Determines whether any incoming connection requests are waiting
Start() Starts listening for incoming requests
Stop() Stops listening for incoming requests

Property Tool Get/Set Description
LocalEndpoint Get. Gets the local EndPoint to which the TcpListener is bound

Once you have constructed a TcpListener object, you can have it start listening on the port that you passed in by calling the Start() method. Now that you have a TcpListener socket that is awaiting a connection, let's take a brief look at network streams.

Using Network Streams

The System.Net.Sockets.NetworkStream class is used for both sending and receiving data over a TCP socket. To create a NetworkStream object, use one of the following constructors:

public NetworkStream(Socket socket);
public NetworkStream(Socket socket, bool ownsSocket);
public NetworkStream(Socket socket, FileAccess access);
public NetworkStream(Socket socket, FileAccess access, bool 
  ownsSocket);

Each constructor specifies a Socket class with which the new stream object should be associated. The ownsSocket parameter should be set to TRUE if you want the Stream object to assume ownership of the socket. The access parameter can be used to specify any FileAccess values for determining access to the stream (such as Read, Write, or ReadWrite).

In addition, you can use the TcpClient.GetStream() method (as you will see in the next section) to get the NetworkStream for the active connection.

The NetworkStream class supports the methods and properties described in Table 12.9.

Table 12.9 NetworkStream Class Methods and Properties

Method Description
BeginRead() Begins an asynchronous Read() operation
BeginWrite() Begins an asynchronous Write() operation
Close() Closes the NetworkStream
CreateWaitHandle() Creates a WaitHandle object for handling asynchronous operation blocking events
Dispose() Releases resources used by the NetworkStream object
EndRead() Ends asynchronous Read() operation
EndWrite() Ends asynchronous Write() operation
Read() Reads from the NetworkStream
ReadByte() Reads a byte from the NetworkStream
Write() Writes to the NetworkStream
WriteByte() Writes a byte to the NetworkStream

Property Get/Set Description
CanRead Get Returns TRUE if the NetworkStream supports reading.
CanWrite Get Returns TRUE if the NetworkStream supports reading.
CanWrite Get Returns TRUE if the NetworkStream supports reading.
CanWrite Get td Returns TRUE if the NetworkStream supports write operations
DataAvailable Get Returns TRUE if the NetworkStream has data to be read
Length Get Returns the amount of data waiting to be read on the stream

The following example shows how you can use the NetworkStream class to send data to a client that is connected to a TcpListener object:

// Create a socket that is listening for incoming connections on // port 8080
string hostName = System.Net.Dns.GetHostName();
System.Net.IPAddress localIPAddress =
   System.Net.Dns.Resolve(hostName).AddressList[0];
System.Net.Sockets.TcpListener tcpServer = new    
TcpListener(localIPAddress, 8080);
// Start listening synchronously
tcpServer.Start();
// Get the client socket when a request comes in
Socket tcpClient = tcpServer.AcceptSocket();
// Make sure the client is connected
if(tcpClient.Connected == false)
   return;
// Create a network stream to send data to the client
NetworkStream clientStream = new NetworkStream(tcpClient);
// Write some data to the stream
byte[] serverBytes = System.Text.Encoding.ASCII.GetBytes(
   "Howdy. You've connected!rn");
clientStream.Write(serverBytes, 0, serverBytes.Length);
// Immediately disconnect the client
tcpClient.Shutdown(SocketShutdown.Both);
tcpClient.Close();

TCP Clients

To establish a connection with a TCP server listening on a specific port, you use the System.Net.Sockets.TcpClient class. Its constructor is defined as follows:

public TcpClient();
public TcpClient(IPEndPoint localEP);
public TcpClient(string hostname, int port); 

The TcpClient class has the methods and properties described in Table 12.10.

Table 12.10 TcpClient Class Methods and Properties

Method Description
Close() Closes the TcpClient socket.
Connect() Connects to a remote host.
GetStream() Gets the NetworkStream object to send and receive data

Property Get/Set Description
LingerState Get/set User accounts, group accounts, delegation administration, GPO management.
LingerState Get/set Gets or sets the socket linger time
NoDelay Get/Set Set to TRUE to disable the delay on a socket when the receive buffer is not full
ReceiveBufferSize Get/Set Gets or sets the receive buffer size
SendBufferSize Get/Set sets the send buffer size

Now that you have looked at both of the TCP client and server classes, let's examine how you could use the TcpListener class to write a small (and extremely simple) Web server that runs on the Pocket PC:

using System;
using System.Data;
using System.Net.Sockets;
namespace TCPServer {
   class WebServer {
      static void Main(string[] args) {
         // Create a socket that is listening for incoming          
// connections on port 80.
         string hostName = System.Net.Dns.GetHostName();
         System.Net.IPAddress localIPAddress =
            System.Net.Dns.Resolve(hostName).AddressList[0];
         System.Net.Sockets.TcpListener tcpServer = new
            TcpListener(localIPAddress, 80);
         // Start listening synchronously and wait for an 
         // incoming socket
         tcpServer.Start();
         Socket tcpClient = tcpServer.AcceptSocket();
         // Make sure the client is connected
         if(tcpClient.Connected == false)
            return;
         // Create a network stream that we will use to send         
 // and receive data.
         NetworkStream clientStream = new NetworkStream           
 (tcpClient);
         // Get a basic request.
         byte[] requestString = new byte[1024];
         clientStream.Read(requestString, 0, 1024);
         // Do something with the client request here.          
// Typically, you'll need to parse the request, open the         
 // file and send the contents back. For this example,         
 // we'll just write out a simple HTTP response to the          
// stream.
         byte[] responseString =             
System.Text.Encoding.ASCII.GetBytes("HTTP/1.0            
200 OKrnrnTest Reponsernrn");
         clientStream.Write(responseString, 0,             
responseString.Length);
         // Disconnect the client
         tcpClient.Shutdown(SocketShutdown.Both);
         tcpClient.Close();
      }
   }
}

Let's also take a look at the code for a small client that requests a Web page from the server:

using System;
using System.Data;
using System.Net.Sockets;
namespace TCPWebClientTest {
   class WebClientTest {
      static void Main(string[] args) {
         // Create a socket that will grab a Web page
         System.Net.Sockets.TcpClient tcpWebClient = new            
 TcpClient();
         // Set up the HTTP request string to get the main          
// index page
         byte[] httpRequestBytes = System.Text.Encoding.            
ASCII. GetBytes("GET / HTTP/1.0rnrn");
         // Connect the socket to the server
         tcpWebClient.Connect("www.microsoft.com", 80);
         // Make sure we are connected
         if(tcpWebClient == null)
            return;
         // Create a network stream that we will use to send          
// and receive data.
         NetworkStream webClientStream = tcpWebClient.            
GetStream();
         // Send the request synchronously
         webClientStream.Write(httpRequestBytes, 0,             
httpRequestBytes.Length);
         // Get the response from the request. We will continuously          
// request 4096 bytes from the response stream and concat          
// the string into the strReponse variable.
         string strResponse = "";
         byte[] httpResponseBytes = new byte[4096];
         int bytesRecv = webClientStream.Read            
(httpResponseBytes, 0, httpResponseBytes.Length);
         strResponse = System.Text.Encoding.ASCII.            
GetString(httpResponseBytes, 0, bytesRecv);
         while(bytesRecv > 0) {
            bytesRecv = webClientStream.Read               
(httpResponseBytes, 0, httpResponseBytes.Length);
            strResponse = strResponse + System.Text.Encoding.               
ASCII.GetString(httpResponseBytes, 0, bytesRecv);
         }
         // At this point, the strResponse string has the          
// Web page. Do something with it
         // Clean up the socket
         tcpWebClient.Close();
      }
   }

Sending and Receiving Data over UDP

Both the sending and receiving of a datagram (or packet) over a connectionless socket is handled by the System.Net.Sockets.UdpClient class. A new UdpClient object is created by using one of the following constructors:

public UdpClient();
public UdpClient(int port);
public UdpClient(IPEndPoint localEP);
public UdpClient(string hostname, int port); 

The UdpClient class supports the methods and properties described in Table 12.11.

Table 12.11 UdpClient Class Methods and Properties

Method Description
Close() Closes the UDP socket
Connect() Connects to a remote host
Connect(DropMulticastGroup() Connects to a remote host
JoinMulticastGroup() Joins a multicast group
Receive() Receives a UDP datagram from a remote host
Send() Sends a UDP datagram to a remote host

Property Get/Set Use Description
Active Get/set Indicates whether a connection has been made to a remote host,
Client Get/set Indicates Gets or sets the socket handle

The following code shows how you can create a socket that sends a UDP datagram to a specific host and port:

using System;
using System.Data;
using System.Net;
using System.Net.Sockets;
namespace udpTest {
   class UdpTestSend {
      static void Main(string[] args) {
         // Setup the target device address. For this sample, we 
         // are assuming it is a machine at 192.168.123.199, and on
          // port  40040.
         System.Net.IPEndPoint ipTarget = new       
      IPEndPoint(System.Net.IPAddress.Parse         
   ("192.168.123.199"), 40040);
         System.Net.Sockets.UdpClient udpSend = new   
          UdpClient(ipTarget);
         // Send a datagram to the target device
         byte[] sendBytes = System.Text.Encoding.ASCII.    
        GetBytes("Testing a datagram buffer");
         udpSend.Send(sendBytes, sendBytes.Length);
      }
   }
}

The code for receiving the datagram would look like the following:

using System;
using System.Data;
using System.Net;
using System.Net.Sockets;
namespace udpTest {
   class UdpTestListen {
      static void Main(string[] args) {
         // Listen for datagrams on port 40040
         System.Net.Sockets.UdpClient udpListener = new  
           UdpClient();
         if(udpListener == null)
            return;
         // Create an endpoint for the incoming datagram
         IPEndPoint remoteEndPoint = new IPEndPoint     
       (IPAddress.Any, 40040);
         // Get the datagram
         byte[] recvBytes = udpListener.Receive(ref       
      remoteEndPoint);
         string returnData = System.Text.Encoding.ASCII.       
     GetString(recvBytes, 0, recvBytes.Length);
         // Do something with the data.... 

Use the following table of contents to navigate to chapter excerpts, or click here to view Chapter 12 in its entirety.



.NET Compact Framework
  Home: Introduction
 Part 1: .NET Compact Framework
 Part 2: Networking with the Compact Framework
 Part 3: Winsock, .NET and the Compact Framework
 Part 4: Internet Protocols and the .NET Pluggable Protocol Mode
 Part 5: Consuming Web Services and the Handheld Device
 Part 6: Pocket PC and P/Invoke
ABOUT THE BOOK:   
Pocket PC Network Programming is a comprehensive tutorial and reference for writing network applications on Pocket PC 2002 and Pocket PC 2002 Phone Edition devices. It explains how the Pocket PC communicates with the Internet, with other mobile devices, and with networks. Click here to purchase the book from Addison-Wesley.
ABOUT THE AUTHOR:   
Steve Makofsky is a software design engineer on Microsoft's .NET XML Messaging team. In addition to having been a Microsoft Embedded MVP, he has worked on several commercial Windows CE products, including the award-winning bUSEFUL Utilities 1.0 and 2.0 (Best of Comdex Utility 1998/1999). Steve coauthored Teach Yourself Windows CE Programming in 24 Hours (Sams, 1999) and has published several magazine articles on .NET and mobile device development. When not working on cool embedded projects, Steve likes to drink lattes and hike on Mt. Everest.
This was first published in December 2006

Dig deeper on Application Servers and Management Solutions

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

MicroscopeUK

SearchCloudProvider

SearchSecurity

SearchStorage

SearchNetworking

SearchCloudComputing

SearchConsumerization

SearchDataManagement

SearchBusinessAnalytics

Close