新增 tcp、http server
This commit is contained in:
parent
7d42c5c928
commit
155206f77a
24
tools/server/http-server.js
Normal file
24
tools/server/http-server.js
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
const http = require('http');
|
||||||
|
const url = require('url');
|
||||||
|
|
||||||
|
const port = 8080;
|
||||||
|
const server = http.createServer((request, response) => {
|
||||||
|
console.log("\n\n\n");
|
||||||
|
console.log("当前时间:" + Date.now() + " | " + new Date().toLocaleString() + " | " + new Date().toISOString());
|
||||||
|
console.log("request.method", request.method);
|
||||||
|
let requestUrl = url.parse(request.url, true);
|
||||||
|
console.log("request.url", requestUrl.pathname, requestUrl.query);
|
||||||
|
console.log("request.headers", request.headers);
|
||||||
|
|
||||||
|
request.on("data", (postData) => {
|
||||||
|
console.log("postData", postData.toString());
|
||||||
|
})
|
||||||
|
response.setHeader("Content-Type", "text/json;charset=utf-8");
|
||||||
|
response.write("hello!");
|
||||||
|
response.end();
|
||||||
|
})
|
||||||
|
|
||||||
|
server.listen(port, (error) => {
|
||||||
|
console.log(error);
|
||||||
|
console.log(`server is running at port ${port}`);
|
||||||
|
})
|
34
tools/server/tcp-server.js
Normal file
34
tools/server/tcp-server.js
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
//引入net模块
|
||||||
|
const net = require('net');
|
||||||
|
//实例化一个服务器对象
|
||||||
|
const server = new net.Server();
|
||||||
|
//监听connection事件
|
||||||
|
server.on('connection', function (socket) {
|
||||||
|
console.log('有新的客户端接入');
|
||||||
|
|
||||||
|
//监听data事件
|
||||||
|
socket.on("data", function (data) {
|
||||||
|
//打印数据
|
||||||
|
console.log("接收到数据:[数据开始]\n" + data.toString() + "[数据结束]");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
//设置监听端口
|
||||||
|
server.listen(8124);
|
||||||
|
//设置监听时的回调函数
|
||||||
|
server.on('listening', function () {
|
||||||
|
console.log('服务正在监听中。。。');
|
||||||
|
//获取地址信息
|
||||||
|
let address = server.address();
|
||||||
|
//获取地址详细信息
|
||||||
|
console.log("服务器监听的端口是:" + address.port);
|
||||||
|
console.log("服务器监听的地址是:" + address.address);
|
||||||
|
console.log("服务器监听的地址类型是:" + address.family);
|
||||||
|
});
|
||||||
|
//设置关闭时的回调函数
|
||||||
|
server.on('close', function () {
|
||||||
|
console.log('服务已关闭');
|
||||||
|
});
|
||||||
|
//设置出错时的回调函数
|
||||||
|
server.on('error', function (err) {
|
||||||
|
console.log('服务运行异常', err);
|
||||||
|
});
|
Loading…
Reference in New Issue
Block a user