Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# .NET Server socket
Halo All,
I Will build App server socket for receive data from WP7.5 (mango)
I have search in internet and than found solution for this. (I don't remember where i get this)
but I have problem in server code.
in server code there is no "FORM" just console like cmd.
here Original code:
 
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();
            }
        }
    }
}
 
Sory, this is wp7.1 side. and here server code side:
 
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
 
namespace SocketServer
{
    //public class program
    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;
    }
}
 

now I want to convert this code to "Windows Form" but I Can't because I don't understand, So Please help me how to convert this script, I don't understand this script lol.
Posted 20-May-12 5:43am
Edited 21-May-12 22:55pm
v2

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hi,
 
If you don't understand this really simple piece of code i doubt you'll get very far but remember; the trip to the answer is the most fun.
 
As I see it all you have to do is:
- create a new form,
- add a button (might as well call it send),
- add a onClicked event,
- copy all private methods from the stuff you posted
- call SendButton_Click from your onclick
- add a textbox to the form called "Message" (that's the data)
- add a member variable: private string Host = "192.168.1.1:666";
 
that should make it connect to ip 192.168.1.1 / port 666 and send the data from the textbox.
 
Hope this helps,
 
Cheers,
 
AT
  Permalink  
Comments
bagus bujangga at 22-May-12 4:02am
   
Sorry I am wrong, I was Update my question with server side code.
the first code is for WP7.
How build this ("Server Code") in ("Windows Form")?

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

  Print Answers RSS
0 Maciej Los 315
1 OriginalGriff 273
2 Aajmot Sk 224
3 Marcin Kozub 210
4 Richard MacCutchan 200
0 OriginalGriff 7,853
1 Sergey Alexandrovich Kryukov 7,107
2 DamithSL 5,604
3 Manas Bhardwaj 4,986
4 Maciej Los 4,790


Advertise | Privacy | Mobile
Web04 | 2.8.1411023.1 | Last Updated 22 May 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100