明树Git Lab
Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Submit feedback
Sign in
Toggle navigation
L
letian_backend
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
zengfanpei
letian_backend
Commits
3e9e358b
Commit
3e9e358b
authored
Jul 01, 2025
by
zfp1
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
tcp
parent
2c9f0f51
Changes
2
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
77 additions
and
0 deletions
+77
-0
tcpclient.js
tcpclient.js
+6
-0
tcpserver.js
tcpserver.js
+71
-0
No files found.
tcpclient.js
0 → 100644
View file @
3e9e358b
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
tcpserver.js
0 → 100644
View file @
3e9e358b
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
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment