Mqttを使用したリアルタイム更新2022/04/15
68867 ワード
<template>
<div>
<h3>주문하기</h3>
주문할 물품명 : <input type="text" v-model="state.itemno"/><br/>
주문 수량 : <input type="text" v-model="state.buycnt"/><br/>
<button @click="handleBuy">주문하기</button>
</div>
</template>
<script>
import mqtt from 'mqtt';
import {onMounted, reactive} from 'vue';
import axios from 'axios';
export default {
setup () {
const state = reactive({
itemno : 22,
buycnt : 10,
token : sessionStorage.getItem("TOKEN"),
message : '', // 보낼 메세지
client : '', // 접속한 클라이언트 객체
host : '1.234.5.158',
port : 11884, // web용 포트번호
options : {
clean : true, //세션 초기화
reconnectPeriod : 20000, // 주기적인 접속 시간
// 고유값
clientId : 'd219_' + new Date().getTime(),
username : 'ds606', // 아이디
password : 'ds606', // 암호
},
topic : 'ds/class606/#',
qos : 0 // 0부터 2까지의 숫자 // 숫자가 클수록 정확도가 올라감 2를 사용하면 느리지만 정확하게 감
});
const handleBuy = async ()=>{
const url = `/ROOT/api/buy/insert2`;
const headers = {"Content-Type":"application/json", "token":state.token};
const body = {
bcnt : state.buycnt,
item : {
icode : state.itemno
}
}
const response = await axios.post(url, body, {headers});
console.log(response.data);
if(response.data.status === 200) {
console.log('주문성공');
// 신호전송 구현...
sendMessage();
}
};
const createConnection = () => {
const url = `ws://${state.host}:${state.port}`;
try {
state.client = mqtt.connect(url, state.options);
console.log(state.client);
state.client.on('connect', () => {
console.log('connect success!!');
});
state.client.on('error', () => {
console.log('connect error!!');
});
state.client.on('message',(topic, message) => {
console.log(topic, JSON.parse(message));
});
}
catch(e){
console.log('mqtt error', e);
}
};
const sendMessage = () => {
// json object => string : JSON.stringify( )
// string => json object : JSON.parse( )
const payload = JSON.stringify({
userid : 'd219',
msg : state.message } );
// 보낼 토픽, 보내는 내용(문자), QOS(0~2)
state.client.publish('ds/class606/d200', payload, 0, error => {
if(error) {
console.log('publish error', error);
return;
}
});
}
onMounted(()=>{
createConnection();
});
return {state, handleBuy, createConnection}
}
}
</script>
<style lang="scss" scoped>
</style>
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>seller home</title>
</head>
<body style="padding: 10px;">
<h3>seller home화면</h3>
<hr />
<div style="padding: 10px;">
<a th:href="@{/seller/insertitem}">물품등록</a>
<a th:href="@{/seller/insertitembatch}">물품일괄등록</a>
<form th:action="@{/seller/home}" method="get">
<input type="text" name="txt" placeholder="검색어" />
<input type="submit" value="검색" />
</form>
<form th:action="@{/seller/deleteupdatebatch}" method="get">
<input type="submit" name="btn" value="일괄수정" />
<input type="submit" name="btn" value="일괄삭제" />
<table border="1">
<tr>
<th>체크</th>
<th>번호</th>
<th>물품코드</th>
<th>물품명</th>
<th>가격</th>
<th>수량</th>
<th>등록일</th>
<th>버튼</th>
</tr>
<tr th:each="tmp, idx : ${list}">
<td><input type="checkbox" th:value="${tmp.icode}" name="no" /> </td>
<td th:text="${idx.count}"></td>
<td>
<a th:href="@{/seller/home(code=${tmp.icode})}"
th:text="${tmp.icode}"></a>
</td>
<td th:text="${tmp.iname}"></td>
<td th:text="${tmp.iprice}"></td>
<td th:text="${tmp.iquantity}"></td>
<td th:text="${tmp.iregdate}"></td>
<td >
<button th:onclick="|javascript:handleUpdate('${tmp.icode}')|">수정</button>
<button th:onclick="|javascript:handleDelete('${tmp.icode}')|">삭제</button>
</td>
</tr>
</table>
</form>
<th:block th:each="i : ${#numbers.sequence(1, pages)}">
<a th:href="@{/seller/home(page=${i}, txt=${param.txt})}" th:text="${i}"></a>
</th:block>
<hr />
<h3>주문내역</h3>
<table border="1">
<tr>
<th>주문번호</th>
<th>주문수량</th>
<th>주문날짜</th>
<th>물품이름</th>
<th>물품가격</th>
<th>주문자</th>
<th>주문자연락처</th>
</tr>
<tr th:each="tmp : ${list2}">
<td th:text="${tmp.bno}"></td>
<td th:text="${tmp.bcnt}"></td>
<td th:text="${tmp.bregdate}"></td>
<td th:text="${tmp.ItemIname}"></td>
<td th:text="${tmp.ItemIprice}"></td>
<td th:text="${tmp.MemberUname}"></td>
<td th:text="${tmp.MemberUphone}"></td>
</tr>
</table>
<hr />
<p th:text="${_csrf.token}"></p>
</div>
<script src="https://unpkg.com/[email protected]/dist/mqtt.min.js"></script>
<script>
const state = ({
message : '', // 보낼 메세지
client : '', // 접속한 클라이언트 객체
host : '1.234.5.158',
port : 11884, // web용 포트번호
options : {
clean : true, //세션 초기화
reconnectPeriod : 20000, // 주기적인 접속 시간
// 고유값
clientId : 'd219_' + new Date().getTime(),
username : 'ds606', // 아이디
password : 'ds606', // 암호
},
topic : 'ds/class606/#',
qos : 0 // 0부터 2까지의 숫자 // 숫자가 클수록 정확도가 올라감 2를 사용하면 느리지만 정확하게 감
});
const url = `ws://1.234.5.158:11884`;
try {
state.client = mqtt.connect(url, state.options);
console.log(state.client);
state.client.on('connect', () => {
console.log('=====connect success!!=====');
});
state.client.on('error', () => {
console.log('connect error!!');
});
state.client.on('message',(topic, message) => {
console.log(topic, JSON.parse(message));
location.reload(); // F5를 누른 효과
});
state.client.subscribe(state.topic, {qos:state.qos}, (error, res) => {
if(error) {
console.log('subscribe topic error', error);
return;
}
console.log('=====subscribe success!!=====', res);
});
}
catch(e){
console.log('mqtt error', e);
}
function handleUpdate(no){
location.href = "/ROOT/seller/updateitem?code="+ no;
}
function handleDelete(no){
if(confirm('삭제할까요?')){
console.log(no);
// GET으로 삭제 처리 주소창을 바꿈
// location.href = "/ROOT/seller/deleteitem?code="+ no;
// POST로 처리
// <form th:action="@{/seller/deleteitem}" method="post">
var form = document.createElement("form");
form.method = "POST";
form.action = "/ROOT/seller/deleteitem";
// <input type="text" name="code" value="전달되는 번호" />
var input = document.createElement("input");
input.name = "code";
input.value = no;
// 시큐리티를 csrf 토큰값 전송용
var input1 = document.createElement("input");
input1.type = "hidden";
input1.name = "_csrf";
input1.value='[[${_csrf.token}]]';
// input type을 form태그에 추가
form.appendChild(input);
form.appendChild(input1);
// form document에 추가
document.body.appendChild(form);
// <input type="submit">를 누름
form.submit();
}
}
</script>
</body>
</html>
Reference
この問題について(Mqttを使用したリアルタイム更新2022/04/15), 我々は、より多くの情報をここで見つけました https://velog.io/@anrkfl/Mqtt를-이용한-실시간-주문-갱신20220415テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol