Socket based Silverlight Chat Application


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 currently offline.

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...
            //start listening...

            Console.WriteLine("Server started.");

            while (true)
                // Set the event to nonsignaled state.

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

                // Wait until a connection is made before continuing.


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

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.


  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


tobin 23-05-2008
I'm sorry that the app can't connect to the server ,and the sourcecode has many errors;

Michiel 24-05-2008
Hi tobin. Make sure you have the .net framework 3.5 installed, VS 2008 and the Silverlight tools for Visual Studio, then the source code will build without errors.

Andrey Altukhov 06-06-2008
Greate work!

markus 25-06-2008
I cannot connect to the server due to a SocketError which says &quot;Acess Denied&quot;. My first guess would be that the firewall is somehow blocking the socket call, but when I connect from another c# client (non-silverlight) the server is reachable. Everything is done on localhost. Any ideas of how I can get the silevrlight client to connect to the server? Thanks

Michiel 25-06-2008
@markus: <br/> Make sure to also start the included Policy Server (PolicyServer\bin\Debug\PolicyServer.exe). Changes in Silverlight 2 beta 2 prevent direct socket connections without a policy server. When trying to open a socket connection from Silverlight, it first needs to connect to a policy server and find a correct policy file. If that doesn't succeed, it won't be able to connect to the chatserver. It then gives you an Acces Denied error. <br/><br/> When a correct policy file is found on the policy server, it will allow socket connections. See my post on this here: <a href='http://www.michielpost.nl/PostDetail_9.aspx'>http://www.michielpost.nl/PostDetail_9.aspx</a>

Sachin 02-07-2008
Great work. I was working on very same work but till date i was not to work. Hope you solution will bring new light in my work . Thanks a million. Please spent the light on man.

Kat 12-07-2008
When I try to build the code, it only shows up as a blank screen in Firefox (no console applications are opened and the webpage says its done loading without errors). Any suggestions on how to fix this?

Michiel 15-07-2008
@Kat | You need to manually start 2 console applications, the chatserver and the policy server.

Ludovic 26-07-2008
how many connections could the server maintain for this application if the chat server was hosted on a dedicated computer?

Michiel 27-07-2008
@Ludovic | No idea, I haven't done any load testing. You're very welcome to do so and make performance improvements to the code if you like. Let me know :)

Kenny 21-08-2008
I have the Silverlight 2 Beta2 and .net framework 3.5 installed, VS 2008 and the Silverlight tools for Visual Studio. Steps followed: 1. Ran Policy.exe then GoGoGo.bat (in Debug folder) 2. Ran Host.exe (in Debug folder) 3. Ran ChatSocketTestPage.html I get this: &quot;install Microsoft Silverlight&quot; ??? Also error: &quot;connection to server failed....&quot; help!

Eric 22-08-2008
very good work!

Eric 22-08-2008
very good work!

MrHeo 24-08-2008
Hi All, The Silverlight 2 beta 2 can connect to Openfire (XMPP Server) in this way? If yes, could you show me an example. Thanks!

kevin 08-09-2008
Good afternoon!

Hughes 10-09-2008
Thanks for share.

Jatinder 14-10-2008
Michiel, I need help, I have done everything mentioned in the comments but still I am getting error &quot;Connection to the server failed, reload page and try again.&quot; Please let me know what to do and I want to do one more thing, i want to have multi user chat, please let me know how to go about it. Please email me or post the comment here so that i can move ahead with the application

Michiel 14-10-2008
It should work if you follow these steps: 1) Make sure to also start the included Policy Server by double clicking GoGoGo.bat (a command window should appear and it must stay on!) Do not start the policy server directly. Do you have the version with the policy server included? It must be started! 2) Start the Host.exe (also a command window, must stay open) 3) Open the ChatSocketTestPage by using the visual studio build in webserver The address of your page should be something like: http://localhost:80100 and not. C:\develop\etc\

Michael Washington 20-10-2008
Just wanted to drop you a line and say that it works just fine on my Vista computer. I was able to easily get it up and running using IIS7 (I configured ChatSocket_Web as a &quot;Application&quot;). I want to get time to make a module of this for SilverlightDesktop.net. If anyone wants to beat me to it please go for it. I will help anyone who needs assistance. Thank you for providing such a wonderful example.

junsae 20-11-2008
Thank you. very good~~!!

Ambresh 20-11-2008
hello hello hello

Erhan Selim 09-12-2008
Oh My God! It worked properly. Thanks...

Claudio 16-12-2008
Hi, thank you for your job but I've a problem after i've sent the first message. When I send the second message your software raise the error &quot;An asynchronous socket operation is already in progress using this SocketAsyncEventArgs instance.&quot; at the line &quot;_socket.SendAsync(_sendEventArgs);&quot; in the Silverlight application. After I've sent the first message I need to do something to finalize my message? Help me, please. Bye, Claudio

vijay 06-01-2009
Nice Work!!

John 18-01-2009
Can you use this to connect to openfire? If anyone could give me some hints on how to do this I would appreciate it alot! Thanks

eli 28-01-2009
Where is the policy xml file?

Gary 20-02-2009
hi,this program run successfully without any problem in my local computer. but when i try it on LAN with 2 computer, i was not be able to see the message send by each computer. what is the problem?

Michiel 23-02-2009
@Gary, you need to host the Silverlight application on 1 central server/computer. Other computers load the page with the silverlight chat control from that server and then connect to the chatserver that's running on that pc alone. You can't just start the project on multiple computers and expect them to find each other.

Vinit 25-02-2009
Hi Michiel, I had a problem with the duplex communication. I want to send message to particular user only, So can you guide me what to do? I want to send some user related data like username along with the connect request or after the confirmation comes from the server(&quot;New client connected&quot;). But I could not make it. I can't find a way of sending data along with the connection request nor can figure out how to get the ClientSocketPacket object from the list based on the received message.

Sorin 27-02-2009
Michiel, Is this demo the same as https://www106.livemeeting.com/cc/mseventsbmo/view.asx?scan=scanhff ? I have missed the live session and was wondering if I can see the recording; however I am asked a Recording ID which I do not have. Thank you for sharing your code. Sorin

Michiel 02-03-2009
@Sorin, The demo/meeting URL has no relation to this website. I also don't have a code to see it.

Keith 04-03-2009
Awesome demo, thanks. I had a question.. why did you have to use a ShowReveicedTextHandler to change the text box. I tried it without using that and it did not work.. but I was wondering if you could explain why? (or point me in the direction of a msdn post) I can't seem to figure it out, thanks.

Michiel 05-03-2009
@Keith, the receiving of the chat messages is asynchronous, but we need to show the received text in the user interface. So we are on an asynchronous thread and we need to get back to the UI thread, that is why you need to use the Dispatcher: this.Dispatcher.BeginInvoke(handler, new object[] { data });

Gary 05-03-2009
Actually I try to change the IP address(in the source code) to point to the particular PC that I would like to chat with. This method will not work?

Michiel 06-03-2009
@Gary, yes that can work. Read some more about silverlight socket security on MSDN: http://msdn.microsoft.com/en-us/library/cc296248(VS.95).aspx

Luke 09-03-2009
Where are you defining this.Dispatcher? I'm trying to translate what you're doing in here to my application, but I can't figure out where you define it at.

Luke 09-03-2009
I realized the idiocy of my question and found the answer about 30 seconds after posting.

conroy 23-03-2009
Thanks for the intro, great work.

Bruno 25-03-2009
Really a great source that compiled perfectly. Thanks!

Bill 03-04-2009
Great work! I was wondering why you made this a push server, rather than a client poll. If you are going to wait 10 seconds to push messages out, wouldn't it be less strain on the server to let the clients poll? Thanks!

Dave 07-04-2009
Hi Michiel, thanks for your great work.It works and I deploy it to remote server by using remote desktop connection from my computer. Then I run it on remote server and I tested it from my computer. All work fine. But after I closed the remote console for about 15 minutes, the service console application quit. How can you run service console application without quitting from web server, so that everytime we browse this web page and the live sample connects to the service host immediately? Is it service configuration or server configuration? I use Windows 2008 server. Thanks again.

Michiel 11-04-2009
@Bill, this example uses socket communication, there's always a socket open between the client and the server. The 10 second push message is only for demonstration.

Michiel 11-04-2009
@Dave, you can create your own windows service and include the code from the console application. Or you can let the console application open by not logging off your remote desktop connection (just disconnect only).

Richard 25-04-2009
Is it possible to make seperate "chatrooms" with it? Ie all running on the same server. Also can you send other data like classes etc through it?

Ken 29-04-2009
May I try it on WAN with NAT?

Michiel 05-05-2009
@Richard, yes it's all possible, but you have to make it yourself. This is just a proof of concept which shows some basic communication. You can edit the code and add your own functionality.

kapil bhavsat 08-05-2009
How to implement Compression in silverlight ...

sid 06-06-2009
Nice application working on my PC, as Michiel says,without anything change.

alok 18-07-2009
Thank you for the sample application .. it is great! Can you please guide me with the question below I have hosted this application into my local machine and have changed my router NAT properties to port forward requests from Internet to my local machine where the policy and host app are running ... but I cannot bind the socket... How can I go about to achieve this ? Thank You

Naresh 24-07-2009
Iam unable to get the connection object of the server when i use applet id.connect() method, can any one help?? thanks in advane

badr 29-07-2009
hi please tell me how i can run the host.exe on the server it's worked fine on my pc but when i tried to upload it to my site i couldn't start it please help as soon as you can Thank you

Anil Pandey 04-08-2009
Nice piece of code.... Working for me, can you please let me know. how can we start the service gogobat and chat servicve in server machine so that this application can run on server machine.

ChrisNguyen 22-09-2009
I cannot connect to your sample app on this page. I think because I am behind a firewall. Do you have away to get around that without turn off the firewall?

Neal Gabriel 09-11-2010
Hi Michiel, This is awsome. I downloaded the file and its working fine. I appreciate the effort of creating such a good simple chat application; but I have a suggestion. (I know, this is a post created long back) it would have been better if you are able to explain or give a breifing about the application and how it works, I mean the technological working scenario of the application; like a tutorial that we see in codeproject; This is just a suggestion; Once again, thank you so much for sharing such a great source;

KennyWoo 31-12-2010
So helpful. Just one word "awesome" Thanks.

YankovskyAndrey 02-03-2011
Good work!



????? ???????????????? ?? ????? ???? ????????, ?????????? ??????????? ???????? ????????, sildenafil. ???????? ??????????? ???????????? ?????????? ???????????? ? ????????? ??????????. ????? ????, ??????????? ??????????? ??????????, ???????? ??????? viagra ?????????? ???????????? ????????, ???????? ??????? ????? ? ?????????. ????? ???????? ? ??????: http://ilyssamed.ru/include/pages/gde_ghivet_snegurochka.html <a href=http://ilyssamed.ru/include/pages/gde_ghivet_snegurochka.html><img>http://s020.radikal.ru/i711/1702/3a/439cc5c1178b.jpg</img></a>

<a href=http://www.bestgoodbuy.ru/???????????/????????/><img>http://bestgoodbuy.ru/70.png</img></a> ????? ? ?????????? ?? ??????? ?????????? <b><a href=http://www.bestgoodbuy.ru/???????????/???/>??? ??????? ? ?????????</a></b> ?????????, ??? ?????? ???? ? ????"???????": ?? ?????? ?????? ?? ?????, ???????? ???????. ???? ???? ?? ????????? ???????????. ? ????? ???? - 4 ????????. <a href=http://www.bestgoodbuy.ru/?????????/><img>http://bestgoodbuy.ru/71.png</img></a> <b><a href=http://www.bestgoodbuy.ru/???????????/?????????/>?????????</a></b> ?????? ???????? 1,21, 10, 17 ? ???????? 1, 2: ?????? ??? ????? ????? ???????? ? ??????. ????? ?????? "?????? ????? ????" - ??????? - ???????, ??????? - ???????. ?????? ??? ?????? ????? ????????? ????? ???? ? ?????, ??? ????? ? ????????. ????? ????? ????? ?????? ??????, ??????? ????? ?? ???????. ???? ?? ??????????? ??????????. ??????? ????? ?????????? ? ??? ??????? ??????, ? ?????... ?????? ???? ?????? ? ??????, ????????? ?????. <a href=http://www.bestgoodbuy.ru/???????????/??????????/><img>http://bestgoodbuy.ru/72.png</img></a> <b><a href=http://www.bestgoodbuy.ru/???????????/????????????/>????????????</a></b> <a href=http://www.bestgoodbuy.ru/>???? ???????? ? ???????? ??????????! - www.bestgoodbuy.ru</a>

New Comment

E-mail (not published)
Enter the code shown: