deathtaker26 Posted January 24, 2014 Author Share Posted January 24, 2014 Hey guys, it's been a bit since I actually posted on the forums. So, I thought I'd start doing some tutorials, ya know… returning to the community. ANYWAYS, in this tutorial I'm going to go over the basics of sending data from HTML5's web socket library to a console server written using the SuperWebSockets Library in C#, and back to the client WebSockets. It's basically teaching the basics of sending data to make a chat room.Let's get started!**What you need.**An understanding to the rudimentary fundamentals of Web Scripting and ProgrammingThe SuperWebSockets Binaries… can be obtained from here: [http://superwebsocket.codeplex.com/](http://superwebsocket.codeplex.com/)The potential to learn and expand your knowledge in web app development..net framework of 4.0 or higherMicrosoft Visual Studio 2010 express or higher (I use VS 2013 express) or MonoDevelope (for linux users, may be a tad different)**Languages used:**C#JavascriptHTML5CSS3**Tutorial Level: Beginner****Building the Server:**So to start off with, we're going to create by building the server. Open visual studio 2013 express and create a C# Console Application Project. Name it whatever you want, just not something that will be used in the library, DO NOT NAME IT WEBSOCKETSERVER!![](http://eclipseorigins.com/community/filehost/6036f292e66ce56669ec1f215137c87e.png)Next, we're going to add libraries into our references. What this does is allows us to use "using" statements to include api's and functions into our source. So on the right hand side of VS you will see your projects pane. In that panel you're going to want to go down to references and right click it and "Add reference". After this you're going to add ALL the .dll files in the extracted SuperWebSocket Binaries zip.![](http://eclipseorigins.com/community/filehost/6a0cbbebed22d01351a29c8817d2a621.png)Once you're done with that, great! Now its time to start coding. We're going to get started with the code by adding in some libraries with using statements.Add the following code under the rest of your using statements```using SuperSocket;using SuperWebSocket;using SuperWebSocket.Config;using SuperWebSocket.Protocol;using SuperSocket.Common;using SuperSocket.SocketBase;using SuperSocket.SocketEngine;using Newtonsoft.Json;```okay what we just added we're classes and libraries. This adds functions and variables to our code. Some of this code will NOT be use in this tutorial such as the Newtonsoft.Json; library. The reason I added them is for your own sake, these can be used to modify the code later.Carrying on, Now we're going to create a private static variable. This is going to go in your Program class, but before your static void main(). So, let's define our server;```private static WebSocketServer server = new WebSocketServer();```Great, now let's make that server do something. We want to initialize the server in our main function, and at the same time we do this we're going to check for errors. We do this using an If statement. Basically if our setup statement returns false, it means there is an error and our program will write a line to the console, and then exit. The function we're using is server.Setup(int port); Add this to your main void``` if (!server.Setup(25531)) { Console.WriteLine("There was an error starting the server on port 25531, perhaps that port is already in use."); Console.ReadLine(); return; }```Got that? Good, now we're going to add some handlers. If you don't know what a handler is, a handler is an event that takes place when something occurs in your code. In this case you're going to need a handler for when the server receives connections and data.> Oh just realized I forgot to mention, we binded the server to port 25531, so keep that in mind for later.To create a handler we're going to put the following code after our if statement we made in the last step.Note; You will get errors with this code until after the next step, so just disregard them.``` server.NewSessionConnected += new SessionHandler(server_newConnection); server.NewMessageReceived += new SessionHandler(server_newMessage); ```Once added we need to define two new methods: server_newConnection and server_newMessageSo, create the two following private static voids:``` private static void server_newConnection(WebSocketSession session) { } private static void server_newMessage(WebSocketSession session, string message) { }```Okay, now that we have those defined we're going to need to have a statement that waits for you to type "quit" into the console. and once we have that done our main function will be complete. Add this after your handlers:``` while (server.State == ServerState.Running) { if (Console.ReadLine().ToLower() == "quit") { continue; } } server.Stop(); Console.WriteLine("Server closed! Press return or enter to exit..."); Console.ReadLine();```what this does is it constantly checks that the state of our server is equal to Running. If you type "quit" into console it will exit the loop and just stop the server returning the message "Server closed!, Press return or enter to exit…"Now, the final step of creating the server, adding code to our handler functions and adding a sendToAll function to send data to every connected client.The following code will Tell the console when a socket is connected, add it to your server_newConnection() function:```Console.WriteLine("New connection received from " + session.RemoteEndPoint);```Done with that function, now let's create the sendToAll method. Create a new public static void named sendToAll. In this we will use a foreach loop to send data to each session, for each session in server.getAllSessions(); Our arguments for this function will just be a string named message which is the message to send.``` public static void sendToAll(string message) { foreach (WebSocketSession session in server.GetAllSessions()) { session.Send(message); } }```finally, we can finish our server by adding functionality to our last handler, server_newMessage. We want this to echo the message received to the console, then send the message to every client connected. Pretty simple… add the following two lines to server_newMessage() function``` Console.WriteLine(session.RemoteEndPoint + ": " + message); sendToAll(session.RemoteEndPoint + ": " + message);```save your source and run your server. This concludes the SuperWebSocket tutorial, In my next tutorial we'll be making the client. I'll release that tutorial in a few minutes. Link to comment Share on other sites More sharing options...
deathtaker26 Posted January 24, 2014 Author Share Posted January 24, 2014 almost forgot, add server.Start() to your main function before the while statement Link to comment Share on other sites More sharing options...
Matt Posted January 24, 2014 Share Posted January 24, 2014 Moved this out of the Eclipse Q&A board for you ;) If I ever get into C#, I'll look into this. Thanks Crest! Link to comment Share on other sites More sharing options...
deathtaker26 Posted January 24, 2014 Author Share Posted January 24, 2014 though I posted this in tuts sorry Link to comment Share on other sites More sharing options...
JohnPony Posted January 31, 2014 Share Posted January 31, 2014 ``` while (server.State == ServerState.Running) { if (Console.ReadLine().ToLower() == "quit") { continue; } }```I think you mean:``` while (server.State == ServerState.Running) { if (Console.ReadLine().ToLower() == "quit") { break; } }``` Link to comment Share on other sites More sharing options...
jcsnider Posted January 31, 2014 Share Posted January 31, 2014 > ```> while (server.State == ServerState.Running)> {> if (Console.ReadLine().ToLower() == "quit")> {> continue;> }> }> > ```> I think you mean:> > ```> while (server.State == ServerState.Running)> {> if (Console.ReadLine().ToLower() == "quit")> {> break;> }> }> > ```lol nice catch ;) Link to comment Share on other sites More sharing options...
deathtaker26 Posted February 1, 2014 Author Share Posted February 1, 2014 > ```> while (server.State == ServerState.Running)> {> if (Console.ReadLine().ToLower() == "quit")> {> continue;> }> }> > ```> I think you mean:> > ```> while (server.State == ServerState.Running)> {> if (Console.ReadLine().ToLower() == "quit")> {> break;> }> }> > ```no I meant continue. It exits the loop and stops the server. Link to comment Share on other sites More sharing options...
JohnPony Posted February 1, 2014 Share Posted February 1, 2014 > no I meant continue. It exits the loop and stops the server.I don't think you know what you're talking about.Continue will not stop the loop, it will simply jump to the next loop iteration (skipping everything below the continue).What you're looking for is break, which exits the loop entirely.:P Link to comment Share on other sites More sharing options...
deathtaker26 Posted February 1, 2014 Author Share Posted February 1, 2014 > I don't think you know what you're talking about.> > > > Continue will not stop the loop, it will simply jump to the next loop iteration (skipping everything below the continue).> > > > What you're looking for is break, which exits the loop entirely.> > > > :Pbreak exits the case's conditional statementSwitch (i) case 1 break;in this case I don't want to exit the switch conditional I want to exit the while loop. to close the server.EditWHOOPS! Just realized I did this with an if statement, sorry I was thinking of the other way I did it. My bad! You guys are right lol Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now