Click here to Skip to main content
15,895,656 members

How to build Server Socket with c#

bagus bujangga asked:

Open original thread
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:

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();
            }
        }
    }
}


Sory, this is wp7.1 side. and here server code side:

C#
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.
Tags: C#, .NET, Server, Sockets

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



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