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'); })
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!