基于Socket 的 Silverlight 聊天室程序

11-05-2008

Looking for the same application but using WCF Duplex binding instead of sockets?
Check out the Silverlight Chat application with WCF Duplex Binding.

My goal was to build a silverlight chat application.
Silverlight will be my client, and I had to build a host, to host the chatroom. The host needs to be able to push messages to the clients. I am not able to push messages to silverlight using webservices, so therefore I used sockets to push data to the silverlight client.

Live example:

Tip: If there are no people to chat with, invite a friend or open 2 browser windows.


The host is a windows console application which listens for incomming socket calls at port 4530.

Sample code:
//create the listening socket...
            _socketListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 4530);
            //bind to local IP Address...
            _socketListener.Bind(ipLocal);
            //start listening...
            _socketListener.Listen(4);

            Console.WriteLine("Server started.");

            while (true)
            {
                // Set the event to nonsignaled state.
                _allDone.Reset();

                // create the call back for any client connections...
                _socketListener.BeginAccept(new AsyncCallback(OnClientConnect), null);

                // Wait until a connection is made before continuing.
                _allDone.WaitOne();

            }

Our Silverlight chat client will connect to the host.

Sample code:
          //Create connection
            _endPoint = new DnsEndPoint(Application.Current.Host.Source.DnsSafeHost, 4530);
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            args.UserToken = _socket;
            args.RemoteEndPoint = _endPoint;
            args.Completed += new EventHandler<SocketAsyncEventArgs>(OnSocketConnectCompleted);
            _socket.ConnectAsync(args);

The Silverlight client is able to receive pushed messages from the server. But is also able to send messages to the server. The Server has to listen for incoming client messages and push those messages to all connected clients.

Download the full sourcecode of the Silverlight Chat Socket Example here.

Important:

  1. Start Policy Server with GoGoGo.bat
  2. Start ChatHost
  3. Start the Silverlight page via the VISUAL STUDIO WEBSERVER (http://localhost:etc) and not via the file system (C:\etc)

Comments? Questions? E-mail me at contact@michielpost.nl

posted @ 2009-06-28 20:47  Sissynong  阅读(1302)  评论(1编辑  收藏  举报