How to use sockets to send data from a C# application to a server/webpage
Continuing the current them of working with NodeJS and sockets before I go on holiday for a couple of weeks, this post is going to look at how we can send data from a C# application to a server/webpage using Javascript and NodeJS. Previously in this theme we’ve looked at using NodeJS and Socket.IO to create a simple chat application before upgrading and looking at how we can pass data between Javascript and a C# application.
This time, we’re going to look at how we can read data in from the terminal in C#, and display it on a webpage on our local host. For this project, you’re going to need NodeJS installed, along with Socket.IO.
Creating the Javascript file
First of, let’s create our Javascript file, as we’ve done previously. Make a new Javascript file (I’ve called mine “webServer.js”) and paste the following code (comments hopefully provide explanations of what’s going on – if you have any questions feel free to leave a comment).
var app = require('http').createServer(handler); var io = require('socket.io').listen(app); var fs = require('fs'); var mySocket = 0; app.listen(3000); //Which port are we going to listen to? function handler (req, res) { fs.readFile(__dirname + '/index.html', //Load and display outputs to the index.html file function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); }); } io.sockets.on('connection', function (socket) { console.log('Webpage connected'); //Confirmation that the socket has connection to the webpage mySocket = socket; }); //UDP server on 41181 var dgram = require("dgram"); var server = dgram.createSocket("udp4"); server.on("message", function (msg, rinfo) { console.log("Broadcasting Message: " + msg); //Display the message coming from the terminal to the command line for debugging if (mySocket != 0) { mySocket.emit('field', "" + msg); mySocket.broadcast.emit('field', "" + msg); //Display the message from the terminal to the webpage } }); server.on("listening", function () { var address = server.address(); //IPAddress of the server console.log("UDP server listening to " + address.address + ":" + address.port); }); server.bind(41181);
Creating the HTML file
Now that we have our Javascript file, we need an HTML file to display our messages on. Make a new HTML file (I’ve named mine “index.html” – if you name yours something different you will need to change line 10 in the Javascript file accordingly) and populate it with the following mark-up.
<html> <head> <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script> <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> </head> <body> <script> var socket = io.connect('http://localhost'); socket.on('field', function (data) { console.log(data); $("#field").html(data); }); </script> Data from C#: <div id="field"></div> </body> </html>
Creating the C# application
The C# application is fairly simple. It’ll simply read data in from the command line (or, if you chose to implement it, a full UI) and broadcast it to the socket connected to the webpage, and display it on that webpage.
Our main method will handle reading data, while a separate function will handle sending the data to the socket. We’ll be using the same includes as we did previously, which gives us a main method like so:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace mySocketTest { class Program { static void Main(string [] args) { while(true) { String data = Console.ReadLine(); if(data.Equals("exit", StringComparison.OrdinalIgnoreCase)) break; //If the user types "exit" then quit the program SendData("127.0.0.1", 41181, data); //Send data to that host address, on that port, with this 'data' to be sent //Note the 41181 port is the same as the one we used in server.bind() in the Javascript file. System.Threading.Thread.Sleep(50); //Sleep for 50ms } } } }
This handles the data input and checks if the user wishes to exit by typing the word ‘exit’ on its own. If ‘exit’ is included in a sentence, or with other chars, the if statement will return false and will display that data on the webpage.
Displaying the data is handled by the SendData method, which connects to the socket and sends the data on towards its final destination.
public static void SendData(string host, int destPort, string data) { IPAddress dest = Dns.GetHostAddresses(host)[0]; //Get the destination IP Address IPEndPoint ePoint = new IPEndPoint(dest, destPort); byte[] outBuffer = Encoding.ASCII.GetBytes(data); //Convert the data to a byte array Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //Create a socket using the same protocols as in the Javascript file (Dgram and Udp) mySocket.SendTo(outBuffer, ePoint); //Send the data to the socket mySocket.Close(); //Socket use over, time to close it }
Add this below the main method and viola, providing the connection can be established, you’ll now be able to type commands in the C# terminal and have them displayed on the webpage.
Testing the application
To test the application, turn on the Javascript server by getting your command line pointing to the directory of this project and typing
node webServer.js
remembering to replace webServer.js with the name of your Javascript file.
Then navigate to your local host remembering which port you have everything set up on (if you’ve copied the code here, that’ll be port 3000) and start your C# application. If everything has worked correctly, you should see something like the image below between the two terminal windows and a webpage.
That’s it, now you have a C# application which is capable of sending data to a webpage using NodeJS and sockets. You can put a GUI on the C# application and you could end up with a very nice piece of kit communicating with the World Wide Web. The possibilities are practically endless…
Hi Fraser,
We loved your other tutorial that used TCP to send data from javascript to c#. Can we send data from c# to javascript using TCP instead of UDP? If not, is there a way to have bi-directional communication through UDP?
Thanks,
John Worthley
Lachlan Blubaugh
Hi John,
I’ve not tried it myself, but the NetworkStream class has a method to write data in a similar fashion to how it reads data. If you’ve set everything up correctly, using the NetworkStream from the TcpClient to send data would look like this:
TcpClient myClient = new TcpClient();
myClient.Connect(IPAddress.Loopback, 3000);
NetworkStream myStream = myClient.GetStream();
if(myStream.CanWrite) {
byte [] message = new byte[4096];
for(int x =0; x < message.Length; x++) message[x] = Convert.ToByte(x); myStream.Write(message, 0, 4096); //Send the message buffer }
As I say, I've not tried this method myself, but that would be the route I would begin looking at.
Hope this helps.
Best regards,
Fraser
Hi Fraser
Thanks for your practical article. Unfortunately, I faced a problem. I copied the codes correctly and I run it without no problem
in my log console, I see “webpage connected” for several times but after about 10 seconds, “nodemon crashed – waiting for file changes befor starting”
I think the problem is, my js connect for several times and …