How to create a simple chat room with Node.js

不言
Release: 2018-06-30 11:42:16
Original
1787 people have browsed it

This article mainly introduces the relevant information of Node.js to create a simple chat room in detail. It has certain reference value. Interested friends can refer to

to read the relevant knowledge of TCP. , wrote a chat room based on NET.

var net = require('net'); var count = 0, users = {}; var server = net.createServer(function (conn) { console.log('连接到'); conn.write( "\r\n > welcome to node-chat!" + "\r\n > " + count + " other people are connected at this time." + "\r\n > please write your name and press enter: " ); count++; // 代表当前连接的昵称 var nickname; console.log(conn); conn.on('data', function (data) { // 删除\r\n // data = data.replace('\r\n', ' '); // 当前注册的昵称不存在 if (!nickname) { // 用户名存在 if(users[data]) { conn.write('nickname in use'); return; } else { // 用户名给nickname nickname = data; users[nickname] = conn; for (var i in users) { users[i].write('\r\n > ' + nickname + ' join our room \r\n > I: '); } } } else { // 开始聊天 for (var i in users) { if (i != nickname) { users[i].write('\r\n > ' + nickname + ': ' + data); } } } }); conn.on('close', function () { count--; }); conn.setEncoding('utf8'); }); server.listen(3000, function () { console.log('服务器监听端口3000'); })
Copy after login

Running screenshot:

Terminal:

telnet Here are two screenshots Netizen

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

angular2 and nodejs implement the image upload function

SpringBoot and Vue.js before and after implementation End-detached file upload function

#

The above is the detailed content of How to create a simple chat room with Node.js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!