Nestjs在WebSocket部分雖然有封裝了Socket.IO,但我們在寫的時候仍可以直接使用Socket.IO的API,後續實作會直接使用Socket.IO的API,Socket.IO作為最火紅的模組,當然要實際玩一下囉。
import { WebSocketGateway, SubscribeMessage, WsResponse, WebSocketServer, WsException, NestGateway } from '@nestjs/websockets';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/map';
import { CreateUserDTO } from '../Users/DTO/create-users.dto';
import Socket = SocketIO.Socket;
//WebSocket listen port 81,namespace:messages
@WebSocketGateway({ port: 81, namespace: 'messages' })
export class ChatGateway implements NestGateway {
//使用Socket.IO的API
socket: Socket;
constructor() { }
afterInit(server) { }
handleConnection(socket) { }
handleDisconnect(socket) { }
//訂閱pushMessage事件
@SubscribeMessage({ value: 'pushMessage' })
AddMessage(sender, message: string) {
//推訊息給自己的前端畫面。
sender.emit('newMessage', message);
//推訊息給其他已建立連線的前端畫面。
sender.broadcast.emit('newMessage', message);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
#messages { margin-bottom: 40px }
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<title>聊天囉</title>
</head>
<body>
<%= title %>
<ul id="messages"></ul>
<form id='chatForm' action="">
<input id="chatMessage" autocomplete="off" /><button>Send</button>
</form>
<script>
//注意一下server端的namespace是messages,所以要聽的server是ws://localhost:81/messages
const socket = io('ws://localhost:81/messages');
$('#chatForm').submit(function(){
//推訊息
socket.emit('pushMessage', $('#chatMessage').val());
$('#chatMessage').val('');
return false;
});
//監聽新訊息事件
socket.on('newMessage', function(msg){
//顯示訊息
$('#messages').append($('<li>').text(msg));
window.scrollTo(0, document.body.scrollHeight);
});
//監聽連線事件
socket.on('connect', function() {
console.log('Connected');
});
//監聽斷線事件
socket.on('disconnect', function() {
console.log('Disconnected');
});
</script>
</body>
</html>
成功!!
抱歉,正逢妹妹結婚,有點忙碌,所以沒深入去實作,但現在已經作出一個簡單的聊天室,還沒有帳號機制,明天有時間再來實作。
程式碼在github