在 Ubuntu 上使用 Node.js 进行网络编程,你可以使用内置的 http 和 net 模块,或者使用第三方库,如 express。以下是一些基本示例:
- 使用内置的
http模块创建一个简单的 HTTP 服务器:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
将此代码保存为 server.js,然后在终端中运行 node server.js。现在,你可以在浏览器中访问 http://localhost:3000,看到 “Hello World” 消息。
- 使用内置的
net模块创建一个简单的 TCP 服务器:
const net = require('net');
const server = net.createServer((socket) => {
console.log('Client connected');
socket.write('Hello World\n');
socket.on('data', (data) => {
console.log(`Received data: ${data}`);
socket.end();
});
socket.on('end', () => {
console.log('Client disconnected');
});
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
将此代码保存为 tcp_server.js,然后在终端中运行 node tcp_server.js。现在,你可以使用 telnet 或 nc 命令连接到服务器:
telnet localhost 3000
或
nc localhost 3000
连接后,你将看到 “Hello World” 消息,并可以发送数据到服务器。
- 使用
express框架创建一个简单的 Web 服务器:
首先,你需要安装 express:
npm init -y
npm install express
然后,创建一个名为 app.js 的文件,并添加以下代码:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
在终端中运行 node app.js。现在,你可以在浏览器中访问 http://localhost:3000,看到 “Hello World!” 消息。
这些示例仅涉及基本的网络编程概念。你可以根据需要扩展它们,例如添加路由、处理 POST 请求或实现 WebSocket 通信。
以上就是关于“Ubuntu Nodejs 如何进行网络编程”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm