明树Git Lab

Commit 3e9e358b authored by zfp1's avatar zfp1

tcp

parent 2c9f0f51
const net = require('net');
const client = net.connect({ port: 3001 }, () => {
client.write(JSON.stringify({ type: 'greeting', name: 'Bob' }) + '\n');
client.end()
});
\ No newline at end of file
const net = require('net');
const { MongoClient } = require('mongodb');
let mongourl = `mongodb://root:letian2024.@172.16.0.16:27017/letian?authSource=admin`; //内网
const server = net.createServer((socket) => {
socket.on('data', (data) => {
console.log(`收到消息:${data}`);
socket.write(`${data}`);
// connectAndInsert(data);
});
socket.on('end', () => {
console.log("客户端断开连接");
});
});
server.listen(3001, ()=> {
console.log(`tcp server启动,监听端口3001`);
})
async function connectAndInsert() {
// 创建 MongoDB 客户端
const client = new MongoClient(mongourl, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000, // 5秒连接超时
});
try {
// 连接到 MongoDB 服务器
console.log(' 正在连接 MongoDB...');
await client.connect();
console.log('✅ MongoDB 连接成功');
// 获取数据库和集合
const db = client.db("letian");
const collection = db.collection("COLLECTION_NAME");
// 创建示例数据
const userData = {
name: '张三',
email: 'zhangsan@example.com',
age: 30,
createdAt: new Date(),
tags: ['nodejs', 'developer'],
address: {
city: '北京',
country: '中国'
}
};
// 插入单个文档
console.log(' 正在插入数据...');
const insertResult = await collection.insertOne(userData);
console.log(`✅ 数据插入成功,文档ID: ${insertResult.insertedId}`);
} catch (err) {
console.error('❌ 数据库操作出错:', err);
} finally {
// 关闭连接
await client.close();
console.log('🔌 MongoDB 连接已关闭');
}
}
// 执行数据库操作
connectAndInsert();
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment