Click here to Skip to main content
15,921,295 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello.
I don't understand about socket in Windows Phone 7 mango.
My project is sending message from device WP7 to my PC and
sending message from my PC to my WP7.
I found simple code to do it. On PC side using console application, this sample just can send from WP7 to mp PC, in console application there no send() method to send message to WP7.

my question is
1. anyone can help me to modification this code?
2. anyone can modification console application to windows form application?


here the code.
Windows Console Application (PC)

C#
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace SocketServer
{
    static class Program
    {
        private const char LengthPrefixDelimiter = ';';
        private static AutoResetEvent _flipFlop = new AutoResetEvent(false);

        static void Main(string[] args)
        {
            // create a socket
            Socket listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp);

            // create a local endpoint
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPEndPoint localEP = new IPEndPoint(ipHostInfo.AddressList.First(), 22222);

            Console.WriteLine("Local address and port : {0}", localEP);

            // bind and listen
            try
            {
                listener.Bind(localEP);
                listener.Listen(1);

                while (true)
                {
                    //Console.WriteLine("Waiting for the next connection...");

                    // accept the next connection
                    listener.BeginAccept(AcceptCallback, listener);

                    _flipFlop.WaitOne();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            listener.Accept();
            listener.Listen(1);

        }

        private static void AcceptCallback(IAsyncResult ar)
        {
            // retrieve the listener, accept
            var listener = (Socket)ar.AsyncState;
            var socket = listener.EndAccept(ar);

            //Console.WriteLine("Connected a client.");

            // trigger new listen
            _flipFlop.Set();

            // start receiving
            var state = new StateObject();
            state.Socket = socket;
            socket.BeginReceive(state.Buffer,
                0,
                StateObject.BufferSize,
                0,
                ReceiveCallback,
                state);
        }

        private static void ReceiveCallback(IAsyncResult ar)
        {
            // retrieve the state and socket
            StateObject state = (StateObject)ar.AsyncState;
            Socket socket = state.Socket;

            // Read data from the client socket.
            int read = socket.EndReceive(ar);

            // flag to indicate there's more data coming
            bool allRead = true;

            // Data was read from the client socket.
            if (read > 0)
            {
                // convert result and output
                string chunk = Encoding.UTF8.GetString(state.Buffer, 0, read);
                state.StringBuilder.Append(chunk);

                // here's our small protocol implementation: check the length-prefix
                string messageLengthText = state.StringBuilder.SubstringByDelimiter(LengthPrefixDelimiter);
                if (state.TotalSize == 0)
                {
                    if (!string.IsNullOrEmpty(messageLengthText))
                    {
                        // get length and set total size
                        var messageLength = Convert.ToInt32(messageLengthText);
                        state.TotalSize = messageLength;
                    }
                    else
                    {
                        // if we haven't received the delimiter yet (very unlikely),
                        // simply continue reading
                        allRead = false;
                    }
                }

                // simply check if we've read all bytes
                allRead = allRead && state.StringBuilder.Length - messageLengthText.Length - 1 == state.TotalSize;
            }

            // check if we need to listen again
            if (!allRead)
            {
                // receive again
                socket.BeginReceive(state.Buffer,
                0,
                StateObject.BufferSize,
                0,
                ReceiveCallback,
                state);
            }
            else
            {
                // output anything we've received
                if (state.StringBuilder.Length > 0)
                {
                    // prepare result
                    string result = state.StringBuilder.ToString();
                    result = result.Substring(result.IndexOf(LengthPrefixDelimiter) + 1);

                    // output result on console
                    Console.WriteLine("Received a message: {0}", result);
                }

                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
                //Console.WriteLine("Closed client connection.");
            }
        }

        public static string SubstringByDelimiter(this StringBuilder sb, char delimiter)
        {
            StringBuilder result = new StringBuilder(sb.Length);
            for (int i = 0; i < sb.Length; i++)
            {
                if (sb[i] == delimiter)
                {
                    return result.ToString();
                }

                result.Append(sb[i]);
            }

            return string.Empty;
        }
    }
    public class StateObject
    {
        public Socket Socket;
        public StringBuilder StringBuilder = new StringBuilder();
        public const int BufferSize = 10;
        public byte[] Buffer = new byte[BufferSize];
        public int TotalSize;
    }
}


And here on WP7 mango Code
XAML :

HTML
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" removed="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
        <TextBlock x:Name="ApplicationTitle" Text="SOCKET SAMPLE" Style="{StaticResource PhoneTextNormalStyle}"/>
        <TextBlock x:Name="PageTitle" Text="Send a msg" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>

    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <StackPanel>
            <TextBlock Text="Host:" />
            <TextBox x:Name="Host"
                     HorizontalAlignment="Stretch"
                     Text="192.168.2.62:22222" />
            <TextBlock Text="Message:" />
            <TextBox x:Name="Message"
                     HorizontalAlignment="Stretch" />
            <Button x:Name="SendButton"
                    Content="Send"
                    Click="SendButton_Click" />
            <TextBlock x:Name="ReceivedText" />
        </StackPanel>
    </Grid>
</Grid>


C# CODE:

C#
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using Microsoft.Phone.Controls;

namespace WP7MangoSocketsTest
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void SendButton_Click(object sender, RoutedEventArgs e)
        {
            // parse the textbox content
            var remoteEndpoint = Host.Text;
            if (string.IsNullOrEmpty(remoteEndpoint) || remoteEndpoint.IndexOf(':') < 0)
            {
                return;
            }

            // split and convert
            string[] remoteEndpointParts = remoteEndpoint.Split(':');
            string host = remoteEndpointParts[0].Trim();
            int port = Convert.ToInt32(remoteEndpointParts[1].Trim());

            // create endpoint
            var ipAddress = IPAddress.Parse(host);
            var endpoint = new IPEndPoint(ipAddress, port);

            // convert text to send (prefix with length)
            var message = string.Format("{0};{1}", Message.Text.Length, Message.Text);
            var buffer = Encoding.UTF8.GetBytes(message);

            // create event args
            var args = new SocketAsyncEventArgs();
            args.RemoteEndPoint = endpoint;
            args.Completed += SocketAsyncEventArgs_Completed;
            args.SetBuffer(buffer, 0, buffer.Length);

            // create a new socket
            var socket = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp);

            // connect socket
            bool completesAsynchronously = socket.ConnectAsync(args);

            // check if the completed event will be raised.
            // if not, invoke the handler manually.
            if (!completesAsynchronously)
            {
                SocketAsyncEventArgs_Completed(args.ConnectSocket, args);
            }
        }

        private void SocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
        {
            // check for errors
            if (e.SocketError != SocketError.Success)
            {
                Dispatcher.BeginInvoke(() => MessageBox.Show("Error during socket operation: "
                    + e.SocketError));

                // do some resource cleanup
                CleanUp(e);
                return;
            }

            // check what has been executed
            switch (e.LastOperation)
            {
                case SocketAsyncOperation.Connect:
                    HandleConnect(e);
                    break;
                case SocketAsyncOperation.Send:
                    HandleSend(e);
                    break;
            }
        }

        private void HandleConnect(SocketAsyncEventArgs e)
        {
            if (e.ConnectSocket != null)
            {
                // simply start sending
                bool completesAsynchronously = e.ConnectSocket.SendAsync(e);

                // check if the completed event will be raised.
                // if not, invoke the handler manually.
                if (!completesAsynchronously)
                {
                    SocketAsyncEventArgs_Completed(e.ConnectSocket, e);
                }
            }
        }

        private void HandleSend(SocketAsyncEventArgs e)
        {
            // show a notification
            Dispatcher.BeginInvoke(() => MessageBox.Show("Sending successful!"));

            // free resources
            CleanUp(e);
        }

        private void CleanUp(SocketAsyncEventArgs e)
        {
            if (e.ConnectSocket != null)
            {
                e.ConnectSocket.Shutdown(SocketShutdown.Both);
                e.ConnectSocket.Close();
            }
        }
    }
}


PLEASE HELP ME :D
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900