Recently started learning node. js, Basic, deep, express,koa,react,keystone,mongress, And so on all kinds of things about node. js, each of the learning of the confusion, because there is no practice, the feeling of learning every point of knowledge like a puzzle, and ultimately did not spell together, so I want to write a few small projects to practice practiced hand, so, there is this article ...
----------------------------------I'm a split line-----------------------------------------------
Well, just write down my little results in the order I wrote the code.
GitHub Address: Https://github.com/maichonglyd/mySmailChat.git The project is running locally
Write code always have a sequence, do the project is also, that first to do what piece after doing what piece will have influence on the whole project, I think, a web chat room, first of all, there should be a Web page, whether it is chat or background no page display can not accurately know the results of code execution, So I first made the page of the page.
<! doctype html>The entire page appears as follows:
650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/7A/A6/wKioL1au1X2TMY5YAABH7tMHXNs422.png "style=" float: none; "title=" chat Room Interface "alt=" Wkiol1au1x2tmy5yaabh7tmhxns422.png "/>
650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/7A/A6/wKioL1au1X-x9w74AAAa4I8ghJo279.png "style=" float: none; "title=" Login Interface "alt=" Wkiol1au1x-x9w74aaaa4i8ghjo279.png "/>
On the page I used the Socket.io in the NPM repository, using the socket to connect to the server, making instant communication, and using Main.js to load the logic processing code on our front-end page, uh, CSS style? All right!! Here's the code for the CSS style:
Index.css
body,html{background-color: #000; vertical-align: center;} div.container{width: 800px;height: 900px;margin-left: auto;margin-right: auto; background-color: #222;} div.titles{text-align: center;background-color: #333;color: #888;p adding: 10px;} Div.chatvalue{width: 790px;margin:5px;height: 690px;overflow:auto;} div.sends{width: 100%;height: 100px;background-color: #333;} Input.writebox{height: 90px;width: 710px;margin-left: 3px;margin-top: 3px;margin-bottom: 3px;font-size: 20px;background-color: #333;border: 1px solid #222; color: # 888;} Input.sendbutton{width: 78px;height: 94px;margin-top: 3px;margin-bottom: 3px;margin-right: 3px;float: right;border: 1px solid #222;background-color: #444;color: #888 ; font-size: 24px;} #loginPage {Position: fixed;top: 0;left: 0;right: 0;bottom: 0;baCkground-color: rgba (50,50,50,0.6);text-align: center;color: #888;d isplay: block; padding-top: 400px;}. systemmsg{width: 100%;text-align: center;color: #f00;}
This content will not have to say more, so far, the front page has been done, the following start to do the service side, first let this page can be displayed:
Server.js:
Const EXPRESS = require (' Express '); const APP = Express (); Const HTTP = require (' http '). Server (APP), const IO = require (' Socket.io ') (HTTP), let userlist = [];http.listen], App.use ("/", Express.static (__ Dirname+ "/web"));
This project relies on packages such as Express, HTTP, Socket.io.
Express is the module in node. js that manages the routing response request and returns the appropriate HTML page based on the requested URL. Here we use a pre-written static page to return to the client, just use Express to specify the path of the page to be returned. Without this package, we need to write the HTML code together with the background JavaScript code in response to the request, which is not very convenient.
HTTP is the core module of node. js, do not know the students to check their own, there is not much to say.
Socket.io is the module used to do the socket connection, we need to bind these packets to each other, so there is
Const HTTP = require (' http '). Server (app); const IO = require (' Socket.io ') (HTTP);
These two lines of code, and then we listened to Port 3000, specifying a static page path to return to the front end.
App.use ("/", Express.static (__dirname+ "/web"));
Here we open the browser input http://localhost:3000 will be able to see our written interface. Of course, the input nickname that figure should not be too positive, the effect of the graph is to need to connect to the server to do some JS operation will look better, well, then I need to put the server rack up, so that the front-end page can be connected:
Server.js:
Io.on ("Connection", userconnction), function userconnction (socket) {Console.log ("a user connecting!!"); Let user = new User ("", socket); Userlist.push (user);} Class User{constructor (name,socket) {this.nickname = Name;this.socket = socket;} SetName (name) {this.nickname = name;} Setsocket () {this.socket = socket;} GetName () {return this.nickname;} Getsocket () {return this.socket;}}
IO Listener Connection Success event, trigger callback function UserConnection, the server will output a sentence stating that a user is connected. Then the user first saved to the array, since it is the background monitoring, that only the front-end to actively connect, OK, then the front-end active connection:
Main.js:
var nickname = ""; window.onload = function () {init ();} function init () {var info= document.getelementbyid ("info"), var nickwrapper= document.getelementbyid ("Nickwrapper"); var nicknameinput= document.getelementbyid ("Nicknameinput"); var loginbtn= document.getElementById ("LoginBtn"); var chatmsg= document.getElementById ("chatmsg"); var chatsendbtn= document.getElementById ("chatsendbtn"); var loginPage= document.getElementById ("LoginPage"); info.textcontent = "Connecting ...." NickWrapper.style.display = "none"; socket = Io.connect ("http://localhost:3000"); Socket.on ("Connect", function () {info.textcontent = "Please enter a nickname! "; nickWrapper.style.display =" Block "; Nicknameinput.focus ();});
Hope that the above piece of Doucument.getelementbyid not let you see faint. I was to use the page in advance to get the elements, the following directly write the name of the variable, no longer write so long.
Here we should connect to the server when the page has just been loaded.
Socket = Io.connect ("http://localhost:3000");
After connecting, turn the input nickname into a mask layer cover all the operating areas, let the user enter the name, the focus point to the input name of the text box.
Socket.on ("Connect", function () {...};
After entering the name we need to upload the name to the background, should be done in the Click event:
Main.js:
Loginbtn.addeventlistener ("click", Function () {var _nickname = nicknameinput.value;if (_nickname.trim (). length!=0) { Socket.emit ("Login", _nickname); nickname = _nickname;} Else{nicknameinput.focus (); nicknameinput.value = "";}},false);
Click on the event we first get the value of the text box, minus the two ends of the space if the length is not equal to 0 that means that the input has content, and then to the background to distribute the event login, and then pass the name passed. At the same time we declare a global variable nickname, record their name.
Socket.emit ("Login", _nickname); nickname = _nickname;
Since we have dispatched the backstage event, the backstage should have the reception place:
Server.js:
Socket.on ("Login", function (data) {if (CheckName (data)) {Socket.emit ("login", "OK"); AddName (Data,socket); Io.sockets.emit ("System_login", Data,userlist.length);} Else{socket.emit ("Login", "have");}); function CheckName (nickname) {for (Let i = 0,length=userlist.length;i<length;i++) {if (nickname = = Userlist[i]. Nickname) {return false;}} return true;} function AddName (name,socket) {for (Let i = 0,length=userlist.length;i<length;i++) {if (Userlist[i].socket = = = Socket {userlist[i].nickname = Name;console.log ("nickname:", Name);}}}
Backstage monitoring the login event distributed by the front desk, through the CheckName function to check if there are duplicate names, if there is to the front desk to distribute the login event, with the parameters "have", told the front desk name has, did not repeat also distributed Lonin event, with the parameter "OK" to tell the foreground name is available. Then write down the names with AddName.
Socket.emit ("Login", "OK"); AddName (Data,socket);
Then tell all the users that there are new users logged in.
Io.sockets.emit ("System_login", data,userlist.length);
Here's an easy place to get confused:
Login event, is this, socket distribution of the event only need to correspond on the line, the front desk distributed login, backstage to have the corresponding acceptance, backstage distributed login, the front desk to have the corresponding reception, but the front desk distributed login, the front desk even if there is login reception is useless.
In the backend notification front-end name can be distributed to the login event, the reception should have the corresponding receive:
Main.js:
Socket.on ("Login", function (data) {if (data = = "OK") {LoginPage.style.display = "none";d ocument.title = "My chat room |" + Nicknam E;chatmsg.focus ();} else if (data = = "have") {info.textcontent = "nickname is occupied, please re-enter!" "; nicknameinput.value =" "; Nicknameinput.focus ();}});
After receiving, by the accompanying parameters to determine whether the name is available, can be used to hide the mask layer, the name of their own display to the page title, the focus to send the message text box, not available on the hint nickname is occupied, empty the input name of the text box, and give focus.
Just backstage also distributed an event, is to tell all users to have a new user logged in, we need to receive this event:
Main.js:
Socket.on ("System_login",function (data,count) {if (data == nickname) {insertmsg ("System_login", "I "," has joined the chat room, currently has " + count + " bit users online ");} Else{insertmsg ("System_login", data, "has joined the chat room, currently has" + count + "users Online");}); Function insertmsg (type,name,msg) {var color = "#f00";var space = ":"; switch (type) {case "System_login":case "system_logout": color= "#f00";space = "";break;case " Userchat ": if (name == nickname) {color = " #080 ";name = " Me ";} else{color = "#088";} space = ":<br/> " break;} Var chatvalue = document.getelementbyid ("Chatvalue");var newnode = Document.createelement ("div");newnode.innerhtml = "<p width= ' 790px ' style= ' word-wrap: Break-word ' ><font color= ' "+color+" > "+name +space+msg+" </font></p> "; Chatvalue.appendchild (NewNode); ChatvaLue.scrolltop = chatvalue.scrollheight;}
Here I did a deal, if the new login user is their own name, it will show "I xxxx";
Here I use the INSERTMSG function to deal with the content to be displayed in the Chat box, in fact, by judging different sources to display different font sizes, colors and separators, because our chat box is a div, we want to add new elements inside to show everyone said, including the system,
var chatvalue = document.getElementById ("Chatvalue"), var newNode = document.createelement ("div"); newnode.innerhtml = " <p width= ' 790px ' style= ' word-wrap:break-word ' ><font color= ' "+color+" ' > ' +name +space+msg+ ' </font> </p> "; Chatvalue.appendchild (NewNode);
Chat history is constantly added from below, the more the following record, the more recent, so we should set the scroll bar to the bottom:
Chatvalue.scrolltop = Chatvalue.scrollheight;
Since there is login there is an exit, exit will also have an event, we should listen to this event, when the supervisor hears that the user exits when the background should tell all the users have been gone:
Server.js:
Socket.on ("disconnect", userdisconnect), function Userdisconnect () {Let i = 0;while (i<userlist.length) {if (userlist [i].socket.disconnected) {if (Userlist[i].nickname.trim (). length!=0) {io.sockets.emit ("System_logout", Userlist[i] . nickname,userlist.length-1);} Userlist.splice (i,1); i--;} i++;}}
Here I use loops to determine if a user has been disconnected:
if (userlist[i].socket.disconnected)
When a user disconnects, send a notification informing all users that the person left, and how many people are left:
Io.sockets.emit ("System_logout", userlist[i].nickname,userlist.length-1);
Well, backstage and send notice, reception also want to receive:
Main.js:
Socket.on ("System_logout", function (Data,count) {insertmsg ("system_logout", data, "has left chat room, currently has" + Count + "users online");});
So far, the preparatory work has been done almost, and the most important thing not to do, that is chat, chat content requires us to click the button to send to the server:
Main.js:
Chatsendbtn.addeventlistener ("click", Function () {var _msg = chatmsg.value;if (_msg.trim (). Length!=0) {Socket.emit (" Userchat ", _msg);} Chatmsg.value = ""; Chatmsg.focus ();});
Send the content length is not a space is not equal to 0, the description is sent with real content, then sent to the backstage:
Socket.emit ("Userchat", _msg);
Also empty the box and focus on it.
Chatmsg.value = ""; Chatmsg.focus ();
Backstage, backstage, come out, I have something to say to everyone:
Server.js:
Socket.on ("Userchat", function (data) {for (Let i = 0,length=userlist.length;i<length;i++) {if (socket = = = Userlist[i] . Getsocket ()) {Let msgobj = {nickname:userlist[i].getname (), Msg:data};io.sockets.emit ("Userchat", MSGOBJ);}});
Backstage in the mind of a lot of people, need to know who you are, and then you want to say and your name to tell everyone, so you need to test the socket corresponding to the name of WHO and then together with the message sent to everyone:
Io.sockets.emit ("Userchat", msgobj);
Well, I forgot to explain: Io.sockets.emit is distributing events to all the clients on the connection, and one socket.emit is sending events to the current socket.
All right, again, the front desk wants to receive:
Main.js:
Socket.on ("Userchat", function (data) {insertmsg ("Userchat", Data.nickname,data.msg);});
At this point, the project was basically finished. Look at the effect.
650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/7A/A7/wKioL1au_k3zAEjpAABWcR9mT-s247.png "title=" Qq20160201132603.png "alt=" Wkiol1au_k3zaejpaabwcr9mt-s247.png "/>
This article is from "__ No acted" blog, please make sure to keep this source http://wuzishu.blog.51cto.com/6826059/1740439
node. JS Learning Notes Concise chat room