Практическое руководство. Использование сокетов

Обновлен: Ноябрь 2007

Платформа .NET Compact Framework поддерживает сетевые соединения на основе сокетов. Дополнительные сведения о программировании сокетов в платформе .NET Compact Framework см. в разделе Программирование сокета.

В этом примере создается экземпляр серверного приложения и экземпляр клиентского приложения, а также показывается, как два приложения обмениваются данными через соединение на основе сокетов. Для сервера используется адрес localhost, поэтому оба приложения запускаются на клиенте. Экземпляр сервера необходимо запустить перед запуском клиента, иначе обмен данными будет невозможен.

Обмен данным через соединение на основе сокетов

  1. Создайте класс с именем Server, реализующий Form, и добавьте в него следующий код:

    Private Shared output As String = ""
    
    
    Public Sub New() 
    
    End Sub
    
    
    Public Sub createListener() 
        ' Create an instance of the TcpListener class.
        Dim tcpListener As TcpListener = Nothing
        Dim ipAddress As IPAddress = Dns.GetHostEntry("localhost").AddressList(0)
        Try
            ' Set the listener on the local IP address.
            ' and specify the port.
            tcpListener = New TcpListener(ipAddress, 13)
            tcpListener.Start()
            output = "Waiting for a connection..."
        Catch e As Exception
            output = "Error: " + e.ToString()
            MessageBox.Show(output)
        End Try
        While True
            ' Always use a Sleep call in a while(true) loop
            ' to avoid locking up your CPU.
            Thread.Sleep(10)
            ' Create a TCP socket.
            ' If you ran this server on the desktop, you could use
            ' Socket socket = tcpListener.AcceptSocket()
            ' for greater flexibility.
            Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
            ' Read the data stream from the client.
            Dim bytes(255) As Byte
            Dim stream As NetworkStream = tcpClient.GetStream()
            stream.Read(bytes, 0, bytes.Length)
            Dim helper As New SocketHelper()
            helper.processMsg(tcpClient, stream, bytes)
        End While
    
    End Sub
    
    
    Shared Sub Main() 
        Application.Run(New Server())
    
    End Sub
    
    
    static string output = "";
    
    public Server()
    {
    }
    
    public void createListener()
    {
        // Create an instance of the TcpListener class.
        TcpListener tcpListener = null;
        IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
        try
        {
            // Set the listener on the local IP address
            // and specify the port.
            tcpListener = new TcpListener(ipAddress, 13);
            tcpListener.Start();
            output = "Waiting for a connection...";
        }
        catch (Exception e)
        {
            output = "Error: " + e.ToString();
            MessageBox.Show(output);
        }
        while (true)
        {
            // Always use a Sleep call in a while(true) loop
            // to avoid locking up your CPU.
            Thread.Sleep(10);
            // Create a TCP socket.
            // If you ran this server on the desktop, you could use
            // Socket socket = tcpListener.AcceptSocket()
            // for greater flexibility.
            TcpClient tcpClient = tcpListener.AcceptTcpClient();
            // Read the data stream from the client.
            byte[] bytes = new byte[256];
            NetworkStream stream = tcpClient.GetStream();
            stream.Read(bytes, 0, bytes.Length);
            SocketHelper helper = new SocketHelper();
            helper.processMsg(tcpClient, stream, bytes);
        }
    }
    
    static void Main()
    {
        Application.Run(new Server());
    }
    
    
  2. В классе Server необходимо обеспечить способ запуска сервера. Например, вызвать метод createListener в событии Click кнопки.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.createListener()
    End Sub
    
    private void button1_Click(object sender, EventArgs e)
    {
        this.createListener();
    }
    
  3. Создайте класс с именем SocketHelper и добавьте в него следующий код:

    Class SocketHelper
        Private mscClient As TcpClient
        Private mstrMessage As String
        Private mstrResponse As String
        Private bytesSent() As Byte
    
        Public Sub processMsg(ByVal client As TcpClient, ByVal stream As NetworkStream, ByVal bytesReceived() As Byte)
            ' Handle the message received and 
            ' send a response back to the client.
            mstrMessage = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length)
            mscClient = client
            mstrMessage = mstrMessage.Substring(0, 5)
            If mstrMessage.Equals("Hello") Then
                mstrResponse = "Goodbye"
            Else
                mstrResponse = "What?"
            End If
            bytesSent = Encoding.ASCII.GetBytes(mstrResponse)
            stream.Write(bytesSent, 0, bytesSent.Length)
    
        End Sub
    End Class
    
    class SocketHelper
    {
        TcpClient mscClient;
        string mstrMessage;
        string mstrResponse;
        byte[] bytesSent;
        public void processMsg(TcpClient client, NetworkStream stream, byte[] bytesReceived)
        {
            // Handle the message received and 
            // send a response back to the client.
            mstrMessage = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length);
            mscClient = client;
            mstrMessage = mstrMessage.Substring(0, 5);
            if (mstrMessage.Equals("Hello"))
            {
                mstrResponse = "Goodbye";
            }
            else
            {
                mstrResponse = "What?";
            }
            bytesSent = Encoding.ASCII.GetBytes(mstrResponse);
            stream.Write(bytesSent, 0, bytesSent.Length);
        }
    }
    

    Сервер создает экземпляр этого класса при подключении клиента.

  4. Создайте класс с именем Client, реализующий Form, и добавьте в него следующий код:

        Shared Sub Connect(ByVal serverIP As String, ByVal message As String) 
        Dim output As String = ""
        Try
                ' Create a TcpClient.
                ' The client requires a TcpServer that is connected
                ' to the same address specified by the server and port
                ' combination.
                Dim port As Int32 = 13
                Dim client As New TcpClient(serverIP, port)
    
                ' Translate the passed message into ASCII and store it as a byte array.
                Dim data(255) As [Byte]
                data = System.Text.Encoding.ASCII.GetBytes(message)
    
                ' Get a client stream for reading and writing.
                ' Stream stream = client.GetStream();
                Dim stream As NetworkStream = client.GetStream()
    
                ' Send the message to the connected TcpServer. 
                stream.Write(data, 0, data.Length)
    
                output = "Sent: " + message
                MessageBox.Show(output)
    
                ' Buffer to store the response bytes.
                data = New [Byte](255) {}
    
                ' String to store the response ASCII representation.
                Dim responseData As String = String.Empty
    
                ' Read the first batch of the TcpServer response bytes.
                Dim bytes As Int32 = stream.Read(data, 0, data.Length)
                responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
                output = "Received: " + responseData
                MessageBox.Show(output)
    
                ' Close everything.
                stream.Close()
                client.Close()
            Catch e As ArgumentNullException
                output = "ArgumentNullException: " + e.ToString()
                MessageBox.Show(output)
            Catch e As SocketException
                output = "SocketException: " + e.ToString()
                MessageBox.Show(output)
            End Try
    
        End Sub
    
        Shared Sub Main() 
            Application.Run(New Client())
    
        End Sub
    
     public Client()
            {
                this.MinimizeBox = false;
            }
    
        static void Connect(string serverIP, string message)
            {
                string output = "";
    
                try
                {
                    // Create a TcpClient.
                    // The client requires a TcpServer that is connected
                    // to the same address specified by the server and port
                    // combination.
                    Int32 port = 13;
                    TcpClient client = new TcpClient(serverIP, port);
    
                    // Translate the passed message into ASCII and store it as a byte array.
                    Byte[] data = new Byte[256];
                    data = System.Text.Encoding.ASCII.GetBytes(message);
    
                    // Get a client stream for reading and writing.
                    // Stream stream = client.GetStream();
                    NetworkStream stream = client.GetStream();
    
                    // Send the message to the connected TcpServer. 
                    stream.Write(data, 0, data.Length);
    
                    output = "Sent: " + message;
                    MessageBox.Show(output);
    
                    // Buffer to store the response bytes.
                    data = new Byte[256];
    
                    // String to store the response ASCII representation.
                    String responseData = String.Empty;
    
                    // Read the first batch of the TcpServer response bytes.
                    Int32 bytes = stream.Read(data, 0, data.Length);
                    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                    output = "Received: " + responseData;
                    MessageBox.Show(output);
    
                    // Close everything.
                    stream.Close();
                    client.Close();
                }
                catch (ArgumentNullException e)
                {
                    output = "ArgumentNullException: " + e;
                    MessageBox.Show(output);
                }
                catch (SocketException e)
                {
                    output = "SocketException: " + e.ToString();
                    MessageBox.Show(output);
                }
            }
    
        static void Main()
            {
                Application.Run(new Client());
            }
    
  5. В классе Client необходимо предоставить метод для подключения пользователя к серверу. Например, вызвать метод Connect в событии Click кнопки.

    Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) 
        ' In this code example, use a hard-coded
        ' IP address and message.
        Dim serverIP As String = "localhost"
        Dim message As String = "Hello"
        Connect(serverIP, message)
    
    End Sub
    
    private void button1_Click(object sender, EventArgs e)
    {
        // In this code example, use a hard-coded
        // IP address and message.
        string serverIP = "localhost";
        string message = "Hello";
        Connect(serverIP, message);
    }
    
  6. Скомпилируйте клиентское и серверное приложение.

  7. Выполните развертывание обоих приложений на устройстве.

  8. Запустите серверное приложение на устройстве и запустите сервер.

  9. Запустите клиентское приложение на устройстве и запустите клиент.

Компиляция кода

Для клиентской программы требуются ссылки на следующие пространства имен:

Для серверной программы требуются ссылки на следующие пространства имен:

См. также

Другие ресурсы

Поддержка сетей и подключений в .NET Compact Framework