A node+express+socket.io development of the chat room source code

Source: Internet
Author: User
Tags emit

First, download the package:

NPM Install Express

NPM Install Socket.io

To create a file:

Server-side code: Server.js

The code is as follows Copy Code

var http=require ("http");
var express=require ("Express");
var sio=require ("Socket.io");

var app=express ();
App.use (Express.static (__dirname+ "/"));

var server=http.createserver (APP);
App.get ("/", Function (req, res) {
Res.sendfile (__dirname+ "/chart.html");
});
Server.listen (1337, "127.0.0.1", function () {
Console.log ("Start listening");
});
var io=sio.listen (server);
var names=[];
Io.sockets.on ("Connection", function (socket) {
Socket.on ("Login", function (name) {
for (Var i=0;i<names.length;i++) {
if (names[i]==name) {
Socket.emit ("duplicate");
Return
}
}
Names.push (name);
Io.sockets.emit ("Login", name);
Io.sockets.emit ("sendclients", names);
});
Socket.on ("Chat", function (data) {
Io.sockets.emit ("chat", data);
});
Socket.on ("Logout", function (name) {
for (Var i=0;i<names.length;i++) {
if (names[i]==name) {
Names.splice (i,1);
Break
}
}
Socket.broadcast.emit ("logout", name);
Io.sockets.emit ("sendclients", names);
});
});

Static page chart.html:

The code is as follows Copy Code
<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>socket.io Chat Room </title>
<link rel= "stylesheet" href= "Chart.css"/>
<script src= "/socket.io/socket.io.js" ></script>
<script type= "Text/javascript" src= "Chart.js" ></script>
<body onload= "Window_onload ()" >
<div id= "DivContainer1" >
<table class= "Tbdlg" border= "0" cellpadding= "3" cellspacing= "0" width= "100%" >
<tr class= "Trdlg" >
&LT;TD class= "Tddlg" width= "5" >
User name:&nbsp;
<input id= "Tbxusername" type= "text" value= "tourists" size= "/>"
<input id= "Btnlogin" type= "button" value= "Login" onclick= "Btnlogin_onclick ();"/>
<input id= "btnlogout" type= "button" value= "Exit" Disabled onclick= "Btnlogout_onclick ();"/>
</td>
</tr>
</table>
</div>
<div id= "Divleft" >
<div id= "Divchat" ></div>
<div id= "DivContainer3" >
<table class= "Tbdlg" border= "0" cellpadding= "3" cellspacing= "0" width= "100%" >
<tr class= "Trdlg" >
&LT;TD valign= "Top" class= "Tddlg" nowrap> dialogue </td>
&LT;TD valign= "Top" class= "Tddlg" >
<textarea id= "tbxmsg" cols= "255" rows= "5" style= "width:100%" ></textarea>
</td>
&LT;TD valign= "Top" class= "Tddlg" >
<input id= "btnsend" type= button "value=" sends "Disabled onclick=" Btnsend_onclick (); "/>
</td>
</tr>
</table>
</div>
</div>
<div id= "divright" > User list:</div>
</body>

Static CSS file:

The code is as follows Copy Code
h1{
Font-family:arial,helvetica,sans-serif;
Font-weight:bold;
font-size:14pt;
Color: #006bb5;
Background-color: #f0f0f0;
border-radius:5px;
border:1px solid #f0f0f0;
padding:5px;
margin:0 0 18px 0;
}
div[id^=divcontainer]{
border:0;
margin:10px 0;
padding:3px;
Background-color: #f0f0f0;
border-radius:5px;
}
div#divleft{
width:85%;
Background-color: #f0f0f0;
Float:left;
}
div#divright{
width:15%;
Background-color:white;
Float:right;
Font-weight:bold;
font-size:12px;
}
div#divchat{
border:0;
margin:10px 0;
padding:3px;
Background-color: #f0f0f0;
border-radius:5px;
position:relative;
height:300px;
Overflow:auto;
font-size:12px;
}
table.tbdlg{
Font-family:verdana,helvetica,sans-serif;
Font-weight:normal;
font-size:12px;
Background-color: #f0f0f0;
}
Tr.trdlg,td.tddlg {
Background-color: #f0f0f0;
font-size:10px;
}
textarea{
Font-family:inherit;
font-size:10pt;
border:1px solid #444;
Background-color:white;
width:100%;
}
Input[type= "button"]{
Font-family:inherit;
border:1px solid #808080;
border-radius:10px;
margin:1px;
Color:white;
Background-color: #81a0b5;
width:100px;
}
Input[type= "button"]:hover{
margin:1px;
Background-color: #006bb5;
}
Input[type= "button"]:active{
margin:1px;
Font-weight:bold;
Background-color: #006bb5;
}
Input[type= "button"]:focus{
margin:0;
Font-weight:bold;
Background-color: #006bb5;
}

Static JS file

The code is as follows Copy Code

The user name used by the Var username,//user when they log in to the Socket.io chat room
socket,//socket Port Object connected to the chat server
tbxusername,//User Name text box
tbxmsg,//Dialog text Box
Display the message area in the divchat;//page
function Window_onload () {
Divchat=document.getelementbyid ("Divchat");
Tbxusername=document.getelementbyid ("Tbxusername");
Tbxmsg=document.getelementbyid ("tbxmsg");
Tbxusername.focus ();
Tbxusername.select ();
}

function Addmsg (msg) {
divchat.innerhtml+=msg+ "<br>";
if (divchat.scrollheight>divchat.clientheight)
Divchat.scrolltop=divchat.scrollheight-divchat.clientheight;
}
function Btnlogin_onclick () {
if (tbxUsername.value.trim () = = "") {
Alert ("Please enter user name");
Return
}
Username=tbxusername.value.trim ();
Socket=io.connect ();
Socket.on ("Connect", function () {
Addmsg ("Connection to chat server has been established.");
Socket.on ("Login", function (name) {
Addmsg ("Welcome to the user" +name+ "into the chat room.");
});
Socket.on ("Sendclients", function (names) {
var Divright=document.getelementbyid ("Divright");
var str= "";
Names.foreach (function (name) {
str+=name+ "<br/>";
});
divright.innerhtml= "user list <br/>";
DIVRIGHT.INNERHTML+=STR;
});
Socket.on ("Chat", function (data) {
Addmsg (data.user+ "said:" +data.msg);
});
Socket.on ("Disconnect", function () {
Addmsg ("The connection to the chat server is disconnected.");
document.getElementById ("Btnsend"). Diabled=true;
document.getElementById ("Btnlogout"). Disabled=true;
document.getElementById ("Btnlogin"). disabled= "";
var Divright=document.getelementbyid ("Divright");
divright.innerhtml= "User list";
});
Socket.on ("Logout", function (name) {
Addmsg ("User" +name+ "has exited the chat room.")
});
Socket.on ("Duplicate", function () {
Alert ("The user name is already in use.");
document.getElementById ("Btnsend"). Disabled=true;
document.getElementById ("Btnlogout"). Disabled=true;
document.getElementById ("Btnlogin"). disabled= "";
});
});

    socket.on ("Error", function (err) {
        addmsg (" There was an error with the link between the chat server. ");
        socket.disconnect ();
        socket.removealllisteners ("Connect");
        io.sockets={};
   });
    socket.emit ("login", userName);
    document.getElementById ("Btnsend"). disabled= "";
    document.getElementById ("Btnlogout"). disabled= "";
    document.getElementById ("Btnlogin"). Disabled=true;
}

function Btnsend_onclick () {
var Msg=tbxmsg.value;
if (msg.length>0) {
Socket.emit ("chat", {user:username,msg:msg});
Tbxmsg.value= "";
}
}
function Btnlogout_onclick () {
Socket.emit ("logout", userName);
Socket.disconnect ();
Socket.removealllisteners ("Connect");
io.sockets={};
Addmsg ("User" +username+ "Exit chat Room:");
var Divright=document.getelementbyid ("Divright");
divright.innerhtml= "User list";
document.getElementById ("Btnsend"). disabled= "Disabled";
document.getElementById ("Btnlogout"). disabled= "Disabled";
document.getElementById ("Btnlogin"). disabled= "";
}

Final interface

You can open several more browsers for testing. This works better.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.