亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
A little about Readline
Manage your dependencies
server
點(diǎn)燃它!
Home CMS Tutorial WordPress Real-time chat using Readline and Socket.io for Node.js

Real-time chat using Readline and Socket.io for Node.js

Aug 31, 2023 pm 06:09 PM
nodejs socketio readline

Real-time chat using Readline and Socket.io for Node.js

Node.js has an underappreciated, but very useful module in its standard library. The Readline module does what it says on the box: reads a line of input from the terminal. This can be used to ask the user a question or two, or create a prompt at the bottom of the screen. In this tutorial, I'm going to demonstrate the capabilities of Readline and make a live CLI chat room powered by Socket.io. Not only can clients send simple messages, they can also send emoticon commands using /me, send private messages using /msg, and allow the use of /nick.

A little about Readline

This is probably the simplest usage of Readline:

var readline = require('readline');

var rl = readline.createInterface(process.stdin, process.stdout);

rl.question("What is your name? ", function(answer) {
	console.log("Hello, " + answer );
	rl.close();
});

We include this module to create a Readline interface using standard input and output streams and then ask the user a one-time question. This is the first use of Readline: asking questions. If you need to confirm something with the user, this might be in the popular form, "Would you like to do this? (y/n)", which is ubiquitous in CLI tools, readline.question () Here's how to do it.

Another feature provided by

Readline is a prompt, which can be customized based on its default ">" characters and temporarily paused to prevent typing. For our Readline chat client, this will be our primary interface. There will be one readline.question() asking for the user's nickname, but everything else will be readline.prompt().

Manage your dependencies

Let’s start with the boring part: dependencies. This project will use the socket.io, socket.io-client packages, and ansi-color. Your packages.json file should look like this:

{
    "name": "ReadlineChatExample",
	"version": "1.0.0",
	"description": "CLI chat with readline and socket.io",
	"author": "Matt Harzewski",
	"dependencies": {
		"socket.io": "latest",
		"socket.io-client": "latest",
		"ansi-color": "latest"
	},
	"private": true
}

Run npm install and that’s it.

server

In this tutorial, we will use a very simple Socket.io server. It doesn’t get more basic than this:

var socketio = require('socket.io');

// Listen on port 3636
var io = socketio.listen(3636);

io.sockets.on('connection', function (socket) {

    // Broadcast a user's message to everyone else in the room
	socket.on('send', function (data) {
		io.sockets.emit('message', data);
    });

});

All it does is receive incoming messages from one client and pass them on to everyone else. For larger scale applications the server may be more robust, but for this simple example it should be enough.

This should be saved in the project directory with the name server.js.

Client: Includes and Settings

Before we get to the fun part, we need to include our dependencies, define some variables, and start the Readline interface and socket connection.

var readline = require('readline'),
socketio = require('socket.io-client'),
util = require('util'),
color = require("ansi-color").set;


var nick;
var socket = socketio.connect('localhost', { port: 3636 });
var rl = readline.createInterface(process.stdin, process.stdout);

At this point, the code is almost self-explanatory. We already have the nickname variable, the socket connection (via the socket.io-client package) and the Readline interface.

In this example Socket.io will connect to localhost via port 3636, of course if you are making a production chat application this will change to your own server's domain and port. (There’s not much point in chatting with yourself!)

Client: Ask for username

Now we are using Readline for the first time! We want to ask the user for a nickname of their choice, which will identify them in the chat room. To do this, we will use Readline's question() method.

// Set the username
rl.question("Please enter a nickname: ", function(name) {
    nick = name;
	var msg = nick + " has joined the chat";
	socket.emit('send', { type: 'notice', message: msg });
	rl.prompt(true);
});

We set the previous nick variable to the value collected from the user, send a message to the server (which will be forwarded to other clients) that our user has joined the chat, and then switch the Readline interface back to prompt mode. The true value passed to prompt() ensures that the prompt is displayed correctly. (Otherwise the cursor may move to position zero on the line and ">" will not be displayed.)

Unfortunately, Readline has frustrating problems with the prompt() method. It doesn't play well with console.log(), which outputs the text to the same line as the prompt character, leaving stray ">" everywhere Characters and other weird characters. To solve this problem, we will not use console.log anywhere in this application except one location. Instead, the output should be passed to this function:

function console_out(msg) {
    process.stdout.clearLine();
	process.stdout.cursorTo(0);
	console.log(msg);
	rl.prompt(true);
}

This slightly hacky solution ensures that the current line in the console is empty and the cursor is at position zero before printing the output. Then it explicitly asks to output the prompt again.

Therefore, in the rest of this tutorial, you will see console_out() instead of console.log().

Client: processing input

Users can enter two types of input: chat and commands. We know the command is preceded by a slash, so it's easy to differentiate between the two.

Readline 有幾個事件處理程序,但最重要的無疑是 line。每當(dāng)在輸入流中檢測到換行符(通過 return 或 Enter 鍵)時,就會觸發(fā)此事件。因此,我們需要為我們的輸入處理程序掛鉤 line。

rl.on('line', function (line) {
    if (line[0] == "/" && line.length > 1) {
		var cmd = line.match(/[a-z]+\b/)[0];
		var arg = line.substr(cmd.length+2, line.length);
		chat_command(cmd, arg);

	} else {
		// send chat message
		socket.emit('send', { type: 'chat', message: line, nick: nick });
		rl.prompt(true);
	}
});

如果輸入行的第一個字符是斜杠,我們就知道這是一個命令,這將需要更多的處理。否則,我們只是發(fā)送常規(guī)聊天消息并重置提示。請注意此處通過套接字發(fā)送的數(shù)據(jù)與上一步中的加入消息之間的差異。它使用不同的 type,因此接收客戶端知道如何格式化消息,并且我們還傳遞 nick?變量。

命令名稱(cmd)和后面的文本(arg)用一些正則表達(dá)式和子字符串魔術(shù)隔離,然后我們將它們傳遞給處理函數(shù)命令。

function chat_command(cmd, arg) {
    switch (cmd) {

		case 'nick':
			var notice = nick + " changed their name to " + arg;
			nick = arg;
			socket.emit('send', { type: 'notice', message: notice });
			break;

		case 'msg':
			var to = arg.match(/[a-z]+\b/)[0];
			var message = arg.substr(to.length, arg.length);
			socket.emit('send', { type: 'tell', message: message, to: to, from: nick });
			break;

		case 'me':
			var emote = nick + " " + arg;
			socket.emit('send', { type: 'emote', message: emote });
			break;

		default:
			console_out("That is not a valid command.");

	}
}

如果用戶輸入 /nick gollum,則 nick 變量將重置為 gollum,它可能是 smeagol?之前,并將通知推送到服務(wù)器。

如果用戶輸入 /msg bilbo 珍貴在哪里?,使用相同的正則表達(dá)式來分隔接收者和消息,然后是一個類型為 tell?被推送到服務(wù)器。這將與普通消息的顯示方式略有不同,并且其他用戶不應(yīng)該看到。誠然,我們過于簡單的服務(wù)器會盲目地將消息推送給每個人,但客戶端會忽略未發(fā)送到正確昵稱的通知。更強(qiáng)大的服務(wù)器可以更加離散。

表情命令的使用形式為/我正在吃第二頓早餐。昵稱以任何使用過 IRC 或玩過多人角色扮演游戲的人都應(yīng)該熟悉的方式添加到表情符號中,然后將其推送到服務(wù)器。

客戶端:處理傳入消息

現(xiàn)在客戶端需要一種接收消息的方法。我們需要做的就是掛鉤 Socket.io 客戶端的 message 事件并適當(dāng)?shù)馗袷交瘮?shù)據(jù)以進(jìn)行輸出。

socket.on('message', function (data) {
    var leader;
	if (data.type == 'chat' && data.nick != nick) {
		leader = color("<"+data.nick+"> ", "green");
		console_out(leader + data.message);
	}
	else if (data.type == "notice") {
		console_out(color(data.message, 'cyan'));
	}
	else if (data.type == "tell" && data.to == nick) {
		leader = color("["+data.from+"->"+data.to+"]", "red");
		console_out(leader + data.message);
	}
	else if (data.type == "emote") {
		console_out(color(data.message, "cyan"));
	}
});

客戶端使用我們的昵稱發(fā)送的類型為 chat?的消息將與昵稱和聊天文本一起顯示。用戶已經(jīng)可以看到他們在 Readline 中輸入的內(nèi)容,因此沒有必要再次輸出它。在這里,我使用 ansi-color 包對輸出進(jìn)行一點(diǎn)著色。這并不是絕對必要的,但它使聊天更容易理解。

類型為 noticeemote 的消息按原樣打印,但顏色為青色。

如果消息是 tell,且昵稱等于此客戶端的當(dāng)前名??稱,則輸出采用 [Somebody->You] Hi! 的形式。當(dāng)然,這并不是非常私密的事情。如果您想查看每個人的消息,您只需取出 && data.to == nick 部分即可。理想情況下,服務(wù)器應(yīng)該知道將消息推送到哪個客戶端,而不是將其發(fā)送給不需要它的客戶端。但這增加了不必要的復(fù)雜性,超出了本教程的范圍。

點(diǎn)燃它!

現(xiàn)在讓我們看看是否一切正常。要對其進(jìn)行測試,請通過運(yùn)行 node server.js 啟動服務(wù)器,然后打開幾個新的終端窗口。在新窗口中,運(yùn)行 node client.js 并輸入昵稱。假設(shè)一切順利,那么您應(yīng)該能夠在他們之間聊天。

希望本教程向您展示了 Readline 模塊的入門是多么容易。您可能想嘗試向聊天應(yīng)用程序添加更多功能,以進(jìn)行更多練習(xí)。最后,查看 Readline 文檔以獲取完整的 API。

The above is the detailed content of Real-time chat using Readline and Socket.io for Node.js. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

Can nodejs write front-end? Can nodejs write front-end? Apr 21, 2024 am 05:00 AM

Yes, Node.js can be used for front-end development, and key advantages include high performance, rich ecosystem, and cross-platform compatibility. Considerations to consider are learning curve, tool support, and small community size.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What projects is nodejs suitable for? What projects is nodejs suitable for? Apr 21, 2024 am 05:45 AM

Node.js is suitable for the following project types: Network and server applications Event-driven applications Real-time applications Data-intensive applications Command-line tools and scripts Lightweight microservices

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

See all articles