paul
paul

Reputation: 233

Integrate a C# client into a node.js + socket.io chat app

As part of learning node.js, I just created a very basic chat server with node.js and socket.io. The server basically adds everyone who visits the chat.html wep page into a real time chat and everything seems to be working!

Now, I'd like to have a C# desktop application take part in the chat (without using a web browser control :)).

What's the best way to go about this?

Upvotes: 3

Views: 3050

Answers (2)

Erdogan Kurtur
Erdogan Kurtur

Reputation: 3685

I created a socket server in nodejs, and connected to it using TcpClient.

using (var client = new TcpClient())
{
    client.Connect(serverIp, port));
    using (var w = new StreamWriter(client.GetStream()))
        w.Write("Here comes the message");
}

Upvotes: 4

Robert C Whitener III
Robert C Whitener III

Reputation: 541

Try using the HttpWebRequest class. It is pretty easy to use and doesn't have any dependencies on things like System.Web or any specific web browser. I use it simulating browser requests and analyzing responses in testing applications. It is flexible enough to allow you to set your own per request headers (in case you are working with a restful service, or some other service with expectations of specific headers). Additionally, it will follow redirects for you by default, but this behavior easy to turn off.

Creating a new request is simple:

HttpWebRequest my_request = (HttpWebRequest)WebRequest.Create("http://some.url/and/resource");

To submit the request:

HttpWebResponse my_response = my_request.GetResponse();

Now you can make sure you got the right status code, look at response headers, and you have access to the response body through a stream object. In order to do things like add post data (like HTML form data) to the request, you just write a UTF8 encoded string to the request object's stream.

This library should be pretty easy to include into any WinForms or WPF application. The docs on MSDN are pretty good.

One gotcha though, if the response isn't in the 200-402 range, HttpWebRequest throws an exception that you have to catch. Fortunately you can still access the response object, but it is kind of annoying that you have to handle it as an exception (especially since the exception is on the server side and not in your client code).

Upvotes: 1

Related Questions