Communication between socket (TCP) and PC in Windows Phone 7

Source: Internet
Author: User

In Windows Phone 7, socket (TCP) communicates with the PC and uses the WP7 simulator to communicate with the simple TCP Service on the PC.


The tcp client establishes a socket connection, sends and receives data, and closes the established socket.


using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

// manually added
using System.Net.Sockets;
using System.Threading;
using System.Text;

namespace SocketClientTest
{
    public class SocketClient
    {
        Socket socket = null;

        // event object for notification when an asynchronous operation is completed
        static ManualResetEvent socketDone = new ManualResetEvent (false);

        // The asynchronous operation exceeds the time definition. If no response is received within this time, the operation is abandoned.
        const int TIMEOUT_MILLISECONDS = 5000;

        // maximum receive buffer
        const int MAX_BUFFER_SIZE = 2048;

        // Socket is connected to the server at the specified port
        // hostName server name
        // portNumber connection port
        // Return value: the string returned by the connection result
        public string Connect (string hostName, int portNumber)
        {
            string result = string.Empty;

            // Create DnsEndPoint. The server port is passed into this method
            DnsEndPoint hostEntry = new DnsEndPoint (hostName, portNumber);

            socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // create a SocketAsyncEventArgs object for connection requests
            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs ();
            socketEventArg.RemoteEndPoint = hostEntry;

            // Inline event handler for the Completed event.
            // Note: This event handler was implemented inline in order to make this method self-contained.
            socketEventArg.Completed + = new EventHandler <SocketAsyncEventArgs> (delegate (object s, SocketAsyncEventArgs e)
                    {
                        result = e.SocketError.ToString ();
                        // Identifies that the request has completed without blocking the UI thread
                        socketDone.Set ();
                    }
                );

            socketDone.Reset ();
            socket.ConnectAsync (socketEventArg);
            socketDone.WaitOne (TIMEOUT_MILLISECONDS);

            return result;
        }

        public string Send (string data)
        {
            string response = "Operation Timeout";

            if (socket! = null)
            {
                // Create a SocketAsyncEventArgs object and set the object properties
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs ();
                socketEventArg.RemoteEndPoint = socket.RemoteEndPoint;
                socketEventArg.UserToken = null;

                socketEventArg.Completed + = new EventHandler <SocketAsyncEventArgs> (delegate (object s, SocketAsyncEventArgs e)
                        {
                            response = e.SocketError.ToString ();
                            socketDone.Set ();
                        }
                    );

                // Send the data to be sent into the send buffer
                byte [] payload = Encoding.UTF8.GetBytes (data);
                socketEventArg.SetBuffer (payload, 0, payload.Length);

                socketDone.Reset ();
                socket.SendAsync (socketEventArg);
                socketDone.WaitOne (TIMEOUT_MILLISECONDS);
            }
            else
            {
                response = "Socket is not initialized";
            }

            return response;
        }

        public string Receive ()
        {
            string response = "Operation Timeout";

            if (socket! = null)
            {
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs ();
                socketEventArg.RemoteEndPoint = socket.RemoteEndPoint;
                socketEventArg.SetBuffer (new Byte [MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);

                socketEventArg.Completed + = new EventHandler <SocketAsyncEventArgs> (delegate (object s, SocketAsyncEventArgs e)
                        {
                            if (e.SocketError == SocketError.Success)
                            {
                                // Get data from the receive buffer
                                response = Encoding.UTF8.GetString (e.Buffer, e.Offset, e.BytesTransferred);
                                response = response.Trim ('\ 0');
                            }
                            else
                            {
                                response = e.SocketError.ToString ();
                            }

                            socketDone.Set ();
                        }
                    );

                socketDone.Reset ();
                socket.ReceiveAsync (socketEventArg);
                socketDone.WaitOne (TIMEOUT_MILLISECONDS);
            }
            else
            {
                response = "Socket is not initialized";
            }

            return response;
        }

        /// <summary>
        /// Closes the Socket connection and releases all associated resources
        /// </ summary>
        public void Close ()
        {
            if (socket! = null)
            {
                socket.Close ();
            }
        }
    }
}

The tcp client is used as follows:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

/ *
 * Socket communication with PC can be run on Windows Phone 7 emulator. Get the corresponding response from the Simple TCP service.
* /

namespace SocketClientTest
{
    public partial class MainPage: PhoneApplicationPage
    {
        const int ECHO_PORT = 7; // Response port: Used in conjunction with the Simple TCP service of the PC system to respond to the received string
        const int QOTD_PORT = 17; // When Japanese recording port: Used with Simple TCP service of PC system

        // Constructor
        public MainPage ()
        {
            InitializeComponent ();

            txtRemoteHost.Text = "yonghang-pc"; // Computer name: you can view it from Desktop-> Calculated Name-> Properties
            txtInput.Text = "Test socket test"; // string sent
        }

        private void btnEcho_Click (object sender, RoutedEventArgs e)
        {
            // clear log
            ClearLog ();

            // confirm whether the input is valid
            if (ValidateRemoteHostInput () && ValidateEditEchoInput ())
            {
                // Initialize the SocketClient instance
                SocketClient client = new SocketClient ();

                // start to connect with Echo Server
                Log (String.Format ("Connecting to server '{0}' over port {1} (echo) ...", txtRemoteHost.Text, ECHO_PORT), true);
                string result = client.Connect (txtRemoteHost.Text, ECHO_PORT);
                Log (result, false);

                // Send string to Echo Server
                Log (String.Format ("Sending '{0}' to server ...", txtInput.Text), true);
                result = client.Send (txtInput.Text);
                Log (result, false);

                // receive response from Echo Server
                Log ("Requesting Receive ...", true);
                result = client.Receive ();
                Log (result, false);

                // close the socket connection
                client.Close ();
            }

        }

        // Get current Japanese record
        private void btnGetQuote_Click (object sender, RoutedEventArgs e)
        {
            ClearLog ();

            if (ValidateRemoteHostInput ())
            {
                SocketClient client = new SocketClient ();

                Log (String.Format ("Connecting to server '{0}' over port {1} (Quote of the Day) ...", txtRemoteHost.Text, QOTD_PORT), true);
                string result = client.Connect (txtRemoteHost.Text, QOTD_PORT);
                Log (result, false);

                Log ("Requesting Receive ...", true);
                result = client.Receive ();
                Log (result, false);

                client.Close ();
            }
        }

        // determine if there is input
        private bool ValidateEditEchoInput ()
        {
            if (String.IsNullOrWhiteSpace (txtInput.Text))
            {
                MessageBox.Show ("Please enter string to send.");
                return false;
            }

            return true;
        }

        // determine if there is input
        private bool ValidateRemoteHostInput ()
        {
            if (String.IsNullOrWhiteSpace (txtRemoteHost.Text))
            {
                MessageBox.Show ("Please enter host name!");
                return false;
            }

            return true;
        }

       // Output test information in TextBox
        private void Log (string message, bool isOutgoing)
        {
            string direction = (isOutgoing)? ">>": "<<";
            txtOutput.Text + = Environment.NewLine + direction + message;
        }

        // Clear test information
        private void ClearLog ()
        {
            txtOutput.Text = String.Empty;
        }
    }
} 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.