创建websocket服务器
使用createserver创建,使用list监听ip地址和端口号
// websocket服务器创建
// 使用node 文件名开启服务器,使用ctri加c关闭
var websocket = require("nodejs-websocket");
var url = "https://mock.mengxuegu.com/mock/6141aa4b21805563ee1031d6/exam/slidenav";
// 使用createServer创建
websocket.createServer(function(ws) {
// text接收客户端发来的数据
ws.on("text", function(res) {
console.log(res);
// ws.send数据接受成功
ws.send(url);
setInterval(function() {
ws.send(url);
}, 5000000);
})
// error链接触发触发
ws.on("error", function() {
console.log("异常");
// 触发异常的时候关闭
ws.close();
})
// close断开链接时触发
ws.on("close", function() {
console.log("关闭");
})
}).listen(8801, "127.0.0.1")
console.log("websocket服务器创建完成")
创建http服务器
// 搭建http服务器
var http = require("http");
var server = http.createServer(function(req, res) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.end(JSON.stringify({ "name": "xiaoming" }));
// 转化为字符串发送
})
server.listen(8888, "127.0.0.1");
使用form表单链接服务器
<!-- 使用form表单链接服务器 -->
<form action="http://127.0.0.1:8888">
用户名:<input type="text"><input type="submit">
</form>
使用ajax链接http服务器
// http客户端
$(function() {
$.ajax({
url: "http://127.0.0.1:8888",
success: function(res) {
console.log(JSON.parse(res))
// 转化成对象接收
}
})
})
使用ajax链接websocket服务器
var websocket = new WebSocket("ws://127.0.0.1:8801");
websocket.onopen = function() {
console.log("成功");
websocket.send("发送数据");
websocket.onmessage = function(e) {
$.ajax({
url: e.data,
type: "post",
datatype: "json",
success: function(res) {
console.log(res);
}
})
}
websocket.onerror = function() {
console.log("服务器端异常");
websocket.close();
}
websocket.onclose = function() {
console.log("服务器端关闭");
}
}