1.html 中使用
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>NETTY SOCKET.IO DEMO</title>
<base>
<script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
<style>
body {
padding: 20px;
}
#console {
height: 450px;
overflow: auto;
}
.username-msg {
color: orange;
}
.connect-msg {
color: green;
}
.disconnect-msg {
color: red;
}
</style>
</head>
<body>
<div id="console" class="well"></div>
<button id="btnSend" onclick="send()">发送数据</button>
<div class="baseURl">
</div>
<div class="img-box">
</div>
</body>
<script type="text/javascript">
let str_imgSrc = document.querySelector(".img-box");
let str_baseURl=document.querySelector(".baseURl");
var socket;
connect();
function connect() {
var loginUserNum = 'admin';
var opts = {
query: 'loginUserNum=' + loginUserNum
};
socket = io.connect('http://192.168.3.107:9099', opts);
socket.on('connect', function() {
console.log("连接成功");
serverOutput('<span class="connect-msg">连接成功</span>');
});
socket.on('push_event', function(data) {
output('<span class="username-msg">' + data + ' </span>');
console.log(data);
str_imgSrc.innerHTML =
`<img src="data:image/jpg;base64,${data.content}" style="width: 500px;height: 500px;">`
});
socket.on('disconnect', function() {
serverOutput('<span class="disconnect-msg">' + '已下线! </span>');
});
}
function output(message) {
var element = $("<div>" + " " + message + "</div>");
$('#console').prepend(element);
}
function serverOutput(message) {
var element = $("<div>" + message + "</div>");
$('#console').prepend(element);
}
function send() {
console.log('发送数据');
socket.emit('text', '你好');
}
</script>
</html>
2.vue 中使用
npm install vue-socket.io --save
import io from 'socket.io-client'
<template>
<div class="app-container">
<div>SOCKET.IO DEMO</div>
<div class="msg-box">{{msg}}</div>
<img :src="'data:image/jpg;base64,'+str_imgUrl" style="width: 200px;height: 200px;">
</div>
</template>
<script>
import io from 'socket.io-client'
export default {
name: "socket",
data() {
return {
socket: null,
msg: null,
str_imgUrl: '',
}
},
mounted() {
this.initWebSocket();
},
methods: {
initWebSocket() {
var loginUserNum = 'admin';
var opts = {
query: 'loginUserNum=' + loginUserNum
};
this.socket = null;
this.socket = io.connect('http://192.168.3.107:9099', opts);
this.socket.on('connect', () => {
console.log("连接成功");
this.msg = "连接成功";
})
this.socket.on('push_event', data => {
console.log(data);
this.str_imgUrl = data.content;
})
this.socket.on('disconnect', () => {
console.log('连接断开')
this.msg = "连接断开";
})
},
},
};
</script>
<style lang="scss" scoped>
.app-container {
width: 100%;
height: 100%;
text-align: left;
}
</style>
3.uniapp 中使用
|