Socket Server in Windows Phone 8

From the beginning of Windows Phone 8 to support Socket expanded to allow developers to write Socket Server, that is to say, in the case of impermeable intermediary services, developers can write a Windows Phone Server Application to allow other devices connected to the,

which when developing battle line games is a very useful mechanism.


Text / Huang Zhongcheng

Socket Support in Windows Phone 8

  From the beginning of Windows Phone 7.1 will support Socket Programming, developers can directly use the Socket need to develop rapid communication of network applications, but then only supports the Socket Client-Side, simply means that you can not build on a Windows Phone Socket Server

To access other Windows Phone App connections, service must be provided through a mediation by other platforms (such as Windows Client, Web site, etc.), which greatly limits the range of applications Windows Phone Apps Socket.

  From the beginning of Windows Phone 8 to support Socket expanded to allow developers to write Socket Server, that is to say, in the case of impermeable intermediary services, developers can write a Windows Phone Server Application to allow other devices connected to the,

This is a very useful mechanism in the development of Battle matching game.

A Simple Socket Listener

  Usage is very simple, you only need to use StreamSocketListener to build a Server Socket, you can access connections from other devices, such as the following procedure.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Navigation;

using Microsoft.Phone.Controls;

using Microsoft.Phone.Shell;

using SocketServer.Resources;

using Windows.Networking.Sockets;

using Windows.Storage.Streams;

using Windows.Networking;

using Windows.Networking.Connectivity;

using System.Text;


namespace SocketServer

{

    public class ListenInformation

    {

        public HostName Host { get; set; }

        public string DisplayName { get; set; }

    }


    public partial class MainPage : PhoneApplicationPage

    {

        private StreamSocketListener _listener = new StreamSocketListener();

        private List _ips = new List();

        // Constructor

        public MainPage()

        {

            InitializeComponent();

            var hostNames = NetworkInformation.GetHostNames();

            foreach (HostName hn in hostNames)

            {

                ListenInformation info = new ListenInformation() { Host = hn };

                if (hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71) //Wi-Fi

                    info.DisplayName = hn.CanonicalName + "(Wi-Fi)";

                else if (hn.IPInformation.NetworkAdapter.IanaInterfaceType == 244) //cellular

                    info.DisplayName = hn.CanonicalName + "(cellular)";

                else

                    info.DisplayName = hn.CanonicalName;

                _ips.Add(info);

            }

            lstIPs.DisplayMemberPath = "DisplayName";

            lstIPs.ItemsSource = _ips;

        }


        async private void WaitForData(StreamSocket socket)

        {

            var dr = new DataReader(socket.InputStream);

            var dataReaded = await dr.LoadAsync(sizeof(uint));


            if (dataReaded == 0)

                return;


            uint strLen = dr.ReadUInt32();

            await dr.LoadAsync(strLen);

            string msg = dr.ReadString(strLen);

            if (msg.ToLower().Equals("bye"))

            {

                socket.Dispose();

                return;

            }

            Dispatcher.BeginInvoke(() =>

                {

                    lstOutput.Items.Add("recv:" + msg);

                });

            WaitForData(socket);

        }




        void listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)

        {           

           WaitForData(args.Socket);

        }


        private async void Button_Click(object sender, RoutedEventArgs e)

        {

            if (lstIPs.SelectedItem != null)

            {

                ((Button)sender).IsEnabled = false;

                _listener.ConnectionReceived += listener_ConnectionReceived;

                await _listener.BindEndpointAsync(((ListenInformation)lstIPs.SelectedItem).Host, "1067");


                appTitle.Text = "listen on " + _listener.Information.LocalPort;

            }

            else

                MessageBox.Show("please select a ip to listen.");

        }

    }

}

Let me explain a little this program a few key segments.


public MainPage()

        {

            InitializeComponent();

            var hostNames = NetworkInformation.GetHostNames();

            foreach (HostName hn in hostNames)

            {

                ListenInformation info = new ListenInformation() { Host = hn };

                if (hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71) //Wi-Fi

                    info.DisplayName = hn.CanonicalName + "(Wi-Fi)";

                else if (hn.IPInformation.NetworkAdapter.IanaInterfaceType == 244) //cellular

                    info.DisplayName = hn.CanonicalName + "(cellular)";

                else

                    info.DisplayName = hn.CanonicalName;

                _ips.Add(info);

            }

            lstIPs.DisplayMemberPath = "DisplayName";

            lstIPs.ItemsSource = _ips;

        }

In theory, every Windows Phone 8 device should be able to have more than one network address, unless the device does not have a data connection and Wi-Fi, so to start a Socket Server, you must first decide which network address knot to tie where to get all the available network addresses through GetHostNames (),

Then through IanaInterfaceType to designate the type of network address, in general, is 71 Wi-Fi, 244 is a data connection.


private async void Button_Click(object sender, RoutedEventArgs e)

        {

            if (lstIPs.SelectedItem != null)

            {

                ((Button)sender).IsEnabled = false;

                _listener.ConnectionReceived += listener_ConnectionReceived;

                await _listener.BindEndpointAsync(((ListenInformation)lstIPs.SelectedItem).Host, "1067");


                appTitle.Text = "listen on " + _listener.Information.LocalPort;

            }

            else

                MessageBox.Show("please select a ip to listen.");

        }

When the user selects to bind the network address, enabled through here BindEndpointAsync Socket Server, the first parameter is HostName, the second is to listen to the Port information.

When wired access, ConnectionReceived event will be triggered in here to read through the DataReader passed by the Client-side data.


async private void WaitForData(StreamSocket socket)

        {

            var dr = new DataReader(socket.InputStream);

            var dataReaded = await dr.LoadAsync(sizeof(uint));


            if (dataReaded == 0)

                return;


            uint strLen = dr.ReadUInt32();

            await dr.LoadAsync(strLen);

            string msg = dr.ReadString(strLen);

            if (msg.ToLower().Equals("bye"))

            {

                socket.Dispose();

                return;

            }

            Dispatcher.BeginInvoke(() =>

                {

                    lstOutput.Items.Add("recv:" + msg);

                });

            WaitForData(socket);

        }




        void listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)

        {           

           WaitForData(args.Socket);

        }

Client: Windows Phone 8

  After completing the Server side, Client-side is relatively simple.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Navigation;

using Microsoft.Phone.Controls;

using Microsoft.Phone.Shell;

using ClientSocketDemo.Resources;

using Windows.Networking.Sockets;

using Windows.Networking;

using Windows.Storage.Streams;


namespace ClientSocketDemo

{

    public partial class MainPage : PhoneApplicationPage

    {

        private StreamSocket _socket = null;


        // Constructor

        public MainPage()

        {

            InitializeComponent();


            // Sample code to localize the ApplicationBar

            //BuildLocalizedApplicationBar();

        }


        private async void Button_Click(object sender, RoutedEventArgs e)

        {

            _socket = new StreamSocket();

            await _socket.ConnectAsync(new HostName(txtIP.Text), "1067");

            ((Button)sender).IsEnabled = false;

            txtIP.IsEnabled = false;

            btnSend.IsEnabled = true;

            txtSendData.IsEnabled = true;           

        }


        private async void btnSend_Click(object sender, RoutedEventArgs e)

        {

            DataWriter dr = new DataWriter(_socket.OutputStream);

            string data = txtSendData.Text;

            dr.WriteUInt32((uint)data.Length);

            await dr.StoreAsync();

            dr.WriteString(data);

            await dr.StoreAsync();

            dr.DetachStream();

        }

    }

}

ConnectAsync may be connected to through the Socket Server, the first parameter is HostName (IP), the second is the Port.

figure 1

Client: Windows 8 App

  Similarly, you can write Windows Store App client to connect into Windows Phone.


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;


namespace WinSocketClient
{
  
    public sealed partial class MainPage : Page
    {
        private StreamSocket _socket = null;

        public MainPage()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            _socket = new StreamSocket();
            await _socket.ConnectAsync(new HostName(txtIP.Text), "1067");
            ((Button)sender).IsEnabled = false;
            txtIP.IsEnabled = false;
            btnSend.IsEnabled = true;
            txtSendData.IsEnabled = true;
        }

        private async void btnSend_Click(object sender, RoutedEventArgs e)
        {
            DataWriter dr = new DataWriter(_socket.OutputStream);
            string data = txtSendData.Text;
            dr.WriteUInt32((uint)data.Length);
            await dr.StoreAsync();
            dr.WriteString(data);
            await dr.StoreAsync();
            dr.DetachStream();
        }

    }
}


figure 2

Original: Big Box  Socket Server in Windows Phone 8


Guess you like

Origin www.cnblogs.com/chinatrump/p/11516562.html