基于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

转载于:https://www.cnblogs.com/SissyNong/archive/2009/06/28/1512839.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值