【发布时间】:2015-09-18 19:42:41
【问题描述】:
我为聊天客户端编写了以下代码到客户端(客户端 1 到服务器服务器到客户端 2),但出现错误:
socket 上缺少错误处理程序。
类型错误:无法读取未定义的属性“发射”
这是我的服务器端代码。
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(3000);
var users = {};
var reciverusers = {};
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.on("users",function(data){
users[data.uid]=data.uid;
users[data.uname] =data.uname;
//console.log(data);
console.log("User Id is "+users[data.uid]);
console.log("Username is "+users[data.uname]);
console.log(users[data.uname] + " Joined with this Id: " +users[data.uid]);
//console.log("cnsle users : "+users[0]);
});
socket.on("sendmsg", function(msgdata){
console.log(msgdata);
reciverusers[msgdata.recipent]=msgdata.recipent;
reciverusers[msgdata.message]=msgdata.message;
console.log("reciver id "+reciverusers[msgdata.recipent]);
for(var name in users) {
if(users[name] === reciverusers[msgdata.recipent]) {
console.log("yes user exits");
console.log("Sending : "+ reciverusers[msgdata.message]);
io.sockets.emit("rmsg",reciverusers[msgdata.message]);
io.sockets.connected[reciverusers[msgdata.recipent]].emit("rmsg", {'msg':reciverusers[msgdata.message]});
break;
}else{
console.log("No user not exists");
}
}
});
和客户端代码
var username,uid;
var socket = io.connect('http://localhost');
$(".client_name").on("submit", function(){
// Tell the server about it
var username = $("#cleintname").val();
var userid = $("#cliendID").val();
socket.emit("users", {"uname": username,"uid":userid});
$(".client_name").remove();
$("#Clientnm").text(username);
return false;
});
var chat_form = $(".chatform");
chat_form.on("submit", function(){
// Send the message to the server
var reciver_id = $("#reciver_id").val();
var msg = $("#message").val();
socket.emit("sendmsg", {"recipent":reciver_id, "message":msg});
// Empty the form
$("#message").val('');
return false;
});
// Whenever we receieve a message, append it to the <ul>
socket.on("rmsg", function(data){
$("#messages").append(data);
});
它使用以下命令编译: node app.js : 编译 [OK]
当我进入或登录时:它工作正常[OK]
当我向另一个客户端发送消息时:失败 [Not ok] 它给了我以下错误:
用户 ID 为 1
用户名为 test
使用此 ID 加入测试:1
用户 ID 为 2
用户名为 test2
test2 使用此 ID 加入:2
这里工作正常,从这里我尝试向 user2/client2 发送消息,但出现错误
{ 配方:'1',消息:'ssfsfs' }
接收者 ID 1
是的用户退出
发送:ssfsfs
socket 上缺少错误处理程序。
TypeError: 无法读取未定义的属性 'emit'
我尽我所能解释我的代码正在使用socket.io lib新版本
【问题讨论】:
-
ty 用于编辑@Drew Gaynor。我的英语有点差
标签: javascript node.js sockets socket.io-1.0