Click here to Skip to main content
15,936,046 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
this is the code to send a text using socket but i really don't know how to manage the receive code >> can any one help *note that it take the IP and a Port from a single text box



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;
                case SocketAsyncOperation.Receive:
                    Handleresive(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 Handleresive(SocketAsyncEventArgs e)
        {
            if (e.ConnectSocket != null)
            {
                // simply start sending
                bool completesAsynchronously = e.ConnectSocket.ReceiveAsync(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();
            }
        }
    }
}
Posted
Updated 18-Feb-12 4:48am
v2
Comments
Sergey Alexandrovich Kryukov 20-Feb-12 15:34pm    
"I don't know how to manage..." is not descriptive. What is your problem, exactly? This is not a question, but a code dump. Why should we even read it if you don't explain what is the problem?
--SA

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