0
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button onclick="message()">Send</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var app = angular.module('groupChatApp', []);
app.controller('groupChatController', function($scope) {
var socket = io();
$scope.message = function(event){
event.preventDefault();
var msg = document.getElementById("m").value;
if(msg !== ""){
socket.emit('chat message',msg);
}
document.getElementById("m").value="";
}
socket.on('chat message',function(value){
console.log(value);
document.getElementById("messages").innerHTML += "<li>"+value+"</li>";
})
});
</script>
這是我的index.html頁面使用socket.io
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', function(request, response) {
response.sendFile(__dirname + '/index.html');
});
io.on('connection',function(socket){
console.log('a user connected');
socket.on('chat message',function(msg){
console.log('message: '+msg);
io.emit('display',msg);
});
socket.on('disconnect',function(){
console.log('user disconnected')
})
});
http.listen(3000, function() {
console.log("listening on 3000");
});
這是我index.js文件設計一個羣聊。每次發送消息時,用戶都會斷開連接。與JS很好地工作,而不是角度。任何建議,爲什麼會這樣
在此先感謝
使您的消息發出事件'chatMessage'而不是'chat message',我不確定空格在套接字的發出事件名稱中是否有效。 –