Sockets

The System.Net.Sockets namespace contains classes used to create applications that work directly with the Transmission Control Protocol (TCP) and the User Datagram Protocol (UDP). These classes build on the native socket classes discussed in the Programming with Native Sockets section later in this chapter.

Creating a TCP Client

To illustrate the use of the TCP client classes, we’ll read the index page from the Microsoft Web site. Here is a Java example using the Socket class:

import java.net.*;
import java.io.*;

public class SocketClient {

    public SocketClient() throws IOException, UnknownHostException {
        Socket x_socket = new Socket("www.microsoft.com", 80);
        PrintWriter x_writer =
            new PrintWriter(x_socket.getOutputStream(), true);
        x_writer.println("GET / HTTP/1.0");
        x_writer.println();
        BufferedReader x_reader = new BufferedReader(
            new InputStreamReader(x_socket.getInputStream()));
        String x_str;
        while ((x_str = x_reader.readLine()) != null) {
            System.out.println(x_str);
        }
        x_writer.close();
        x_reader.close();
        x_socket.close();
    }

    public static void main(String[] p_args) throws Exception {
        new SocketClient();
    }
}

This example opens a connection to the HTTP server, sends a message requesting the index page, and then prints the response from the server. After all of the response has been processed, the streams and the socket are closed. This represents a basic HTTP client but doesn’t have any of the knowledge of HTTP that’s available in the WebClient, WebRequest, and WebResponse classes described at the start of this chapter. Here’s the equivalent functionality written in C#:

using System;
using System.Net.Sockets;
using System.IO;

namespace SimpleTCPClient {

    class Client {

        Client() {
            TcpClient x_client
                = new TcpClient("www.microsoft.com", 80);
            NetworkStream x_stream = x_client.GetStream();
            StreamWriter x_writer = new StreamWriter(x_stream);
            StreamReader x_reader = new StreamReader(x_stream);
            x_writer.WriteLine("GET / HTTP/1.0");
            x_writer.WriteLine();
            x_writer.Flush();
            string x_str;
            while ((x_str = x_reader.ReadLine()) != null) {
                Console.WriteLine(x_str);
            }
            x_writer.Close();
            x_reader.Close();
            x_stream.Close();
            x_client.Close();
        }

        static void Main(string[] p_args) {
            new Client();
        }
    }
}

The C# and Java examples are very similar, and the System.Net.Sockets.TcpClient class can be considered as a direct replacement for java.net.Socket. Table 14-12 shows the member mapping between these two classes.

Table 14-12. The Mapping Between the Java Socket Class and the .NET TcpClient Class

java.net.Socket

TcpClient

Comments

bind()

N/A

 

close()

Close()

 

connect()

Connect()

Both classes will automatically connect to the server if the host name and port number are provided as arguments to the constructor.

getChannel()

N/A

 

getInetAddress()

N/A

 

getLocalAddress()

  

getLocalPort()

  

getLocalSocketAddress()

  

getPort()

  

getInputStream()

GetStream()

The NetworkStream class is responsible for both input and output.

getKeepAlive()

N/A

 

getOOBInline()

  

getReuseAddress()

  

getSoTimeout()

  

getReceiveBufferSize()

ReceiveBufferSize

 

setReceiveBufferSize()

  

getSendBufferSize()

setSendBufferSize()

 

SendBufferSize

  

getSoLinger()

LingerState

 

setSoLinger()

  

getTcpNoDelay()

NoDelay

 

setTcpNoDelay()

  

isClosed()

N/A

 

isConnected()

Active

This property is protected.

isInputShutdown()

N/A

Input is shut down with the Close method.

isOutputShutdown()

  

shutdownInput()

  

shutdownOutput()

  

Creating a TCP Server

The System.Net.Sockets.TcpListener class is used to create server applications. Like the TcpClient class, TcpListener provides a simple wrapper around the socket classes and provides a substitute for the java.net.ServerSocket class. Here is a simple TCP server that accepts a single client connection and writes the current time to the server console:

using System;
using System.Net.Sockets;
using System.IO;

namespace SimpleTcpServer {

    class Server {

        Server() {
            TcpListener x_listener = new TcpListener(20172);
            x_listener.Start();
            Console.WriteLine("Waiting for a connection");

            TcpClient x_client = x_listener.AcceptTcpClient();
            Console.WriteLine("Accepted connection");
            StreamWriter x_writer =
                new StreamWriter(x_client.GetStream());
            x_writer.WriteLine("The time is {0}",
                DateTime.Now.ToShortTimeString());
            x_writer.Flush();
            Console.WriteLine("Sent time to client");

            x_client.Close();
            x_listener.Stop();
            Console.WriteLine("Finished");
        }

        static void Main(string[] args) {
            new Server();
        }
    }
}

The TcpListener constructor accepts a port number, which will be used to receive client connections. The Start method begins listening for connections, and the class will continue to do so until the Stop method is called.

New client connections are accepted using either the AcceptTcpClient or AcceptSocket method. The AcceptTcpClient method returns an instance of TcpClient, discussed in the preceding section. The AcceptSocket method returns an instance of System.Net.Sockets.Socket, which is covered in the Programming with Native Sockets section of this chapter.

Note

The Stop method ensures that TcpListener won’t accept new client connections but it won’t terminate connections already accepted with the AcceptTcpClient and AcceptSocket methods. Socket and TcpClient instances must be closed explicitly before the underlying socket can be released.

Once a connection has been accepted, the resulting type can be used to communicate with the client. These operations can be handed off to threaded delegates, but the process of accepting new connections is synchronous. The Socket class allows connections to be accepted asynchronously; see the Programming with Native Sockets section for more details.

Table 14-13 illustrates the mapping between java.net.ServerSocket and System.Net.Sockets.TcpListener.

Table 14-13. The Mapping Between the Java ServerSocket Class and the .NET TcpListener Class

Java ServerSocket Class

.NET TcpListener Class

Comments

accept()

AcceptTcpClient()

TcpListener won’t begin to listen for client connections until the Start method is called.

 

AcceptSocket()

 

bind()

N/A

 

N/A

Start()

Starts listening for client connections.

close()

Stop()

 

isClosed()

N/A

 

getChannel()

N/A

 

getInetAddress()

LocalEndpoint

Returns the EndPoint instance for the TcpListener that contains the address and port details.

getPort()

  

getLocalSocketAddress()

N/A

 

getReceiveBufferSize()

N/A

 

getReuseAddress()

  

getSoTimeout()

  

N/A

Pending()

Returns true if there are pending client connection requests.

Using UDP

The UdpClient is responsible for handling both point-to-point and multicast messages with the UDP protocol; since UDP is a connectionless protocol, the UdpClient class is used by all endpoints. This provides functionality equivalent to that of the java.net.DatagramSocket and java.net.MulticastSocket classes from the Java API.

The UdpClient can be constructed with details of a default host, and the programmer has the choice of supplying host details for each message or using the default by invoking different forms of the Send method. The class provides a Receive method that blocks until a datagram is received. The mapping between the Java DatagramSocket and MulticastSocket classes and the .NET UdpClient class is shown in Table 14-14.

Table 14-14. The Mapping Between the Java DatagramSocket and MulticastSocket Classes and the .NET UdpClient Class

Java DatagramSocket and MulticastSocket Classes

.NET UdpClient Class

Comments

DatagramSocket.bind()

N/A

 

DatagramSocket.isBound()

  

DatagramSocket.close()

Close()

 

DatagramSocket.connect()

Connect()

Binds the UdpClient to a specific host and port.

DatagramSocket.disconnect()

N/A

 

DatagramSocket.getChannel()

N/A

 

DatagramSocket.getInetAddress()

N/A

 

DatagramSocket.getLocalAddress()

  

DatagramSocket.getLocalPort()

  

DatagramSocket.getLocalSocketAddress()

  

DatagramSocket.getReceiveBufferSize()

  

DatagramSocket.getRemoteSocketAddress()

  

DatagramSocket.getReuseAddress()

  

DatagramSocket.getSoTimeout()

  

DatagramSocket.send()

Send()

 

DatagramSocket.receive()

Receive()

 

MulticastSocket.joinGroup()

JoinMulticastGroup()

 

MulticastSocket.leaveGroup()

DropMulticastGroup()

 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset