Home > Article > Web Front-end > Sharing a simple chat room function implemented in nodejs_node.js
Today I will implement a simple chat room, using nodejs in the background, and socket.io to communicate between the client and the server. This is a relatively mature websocket framework.
Initial work
1. Install express and use it to host socket.io and static pages. Command npm install express --save, --save to add the package to the package.json file.
2. Install socket.io, command npm install socket.io --save.
Write server code
First we host the website through express and attach it to the socket.io instance, because socket.io requires the http protocol for the initial connection
var app = express();
app.use(express.static(__dirname));
var server = app.listen(8888);
var ws = io.listen(server);
Write client code
Since the server uses a third-party websokcet framework, the front-end page needs to reference the socket.io client code separately. The source file can be found in the socket.io module. The path under Windows is node_modulessocket.ionode_modulessocket.io-clientdist. Here is For development and compressed versions, just quote the development version by default.The front end mainly handles input nickname checking and message processing. The complete code is as follows: