我几乎从这里发布的教程中学习。 http://www.williammora.com/2013/03/nodejs-tutorial-building-chatroom-with.html
当我完成后,我继续在任何socket.io连接之后得到它:
/socket.io/?EIO=2&transport=polling&t=1407300527964-0 /socket.io/?EIO=2&transport=polling&t=1407300527984-1&sid=NODtj47CA4mdxjdjAAAB /socket.io/?EIO=2&transport=polling&t=1407300528005-2&sid=NODtj47CA4mdxjdjAAAB /socket.io/?EIO=2&transport=polling&t=1407300528008-3&sid=NODtj47CA4mdxjdjAAAB
最终我与套接字断开连接,连接重置。
Connected NODtj47CA4mdxjdjAAAB index.js:28
incomingMessage Object {message: "sdfdfs", name: "Anonymous"} index.js:60
Unable to connect to server
Error {type: "TransportError", description: ReferenceError, stack: (...), message: "parser decode error"}
index.js:70
Connected BhMCUqxOsRBWrmPmAAAC
我可能已经安装了最新的模块而不是package.json
{
"name": "chatTutorial",
"version": "0.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.5.2",
"express": "^4.7.4",
"jade": "^1.5.0",
"jshint": "^2.5.2",
"socket.io": "^1.0.6",
"underscore": "^1.6.0"
}
}
如果您有兴趣,请输入代码 server.js
/**
* Module dependencies:
* - Express
* - Http (to run Express)
* - Body parser (to parse JSON requests)
* - Underscore (because it's cool)
* - Socket.IO (Note: we need a web server to attach Socket.IO to)
*/
var express = require("express")
, app = express()
, http = require("http").Server(app)
, bodyParser = require("body-parser")
, _ = require("underscore")
, io = require("socket.io")(http)
;
/**
* The list of participants in our chatroom. The format of each participants will be:
* {
* id: "sessionId",
* name: "participantName"
* }
*/
/* Server config */
var participants = [];
//Server's IP address
app.set("ipaddr", "127.0.0.1");
//Server's port number
app.set("port", 8080);
// Specify a views folder
app.set("views", __dirname + "/views");
// View engine is Jade
app.set("view engine", "jade");
// Specify where the static content is
app.use(express.static("public", __dirname + "/public"));
//Tells server to support JSON requests
app.use(bodyParser.json());
/* Server routing */
//Handle route "GET /", as in "http://localhost:8080/"
app.get("/", function(request, response) {
//Show a simple response message
// response.send("Server is up and running");
response.render("index0");
});
app.post("/message", function (req, res) {
console.log('getting request', req.body);
// The request body expects a param named "message"
var message = req.body.message;
// If the message is empty or wasn't sent it's a bad request
if(_.isUndefined(message) || _.isEmpty(message.trim())){
// return res.json(400, {error: "Message is invalid"}); //deprecated
return res.status(400).json({error: "Message is invalid"});
}
// We also expect the sender's name with the message
var name = req.body.name;
// Let our chatroom know there was a new message
io.sockets.emit("incomingMessage", {message: message, name: name});
// Looks good, let the client know
// res.json(200, {message: "Message received"}); //deprecated
res.status(200).json({message: "Message received"});
});
/**
* Socket.IO events
*/
io.on("connection", function (socket) {
/**
* When a new user connects to our server, we expect an event called "newUser" and then we'll emit an event called "newConnection" with a list of all participants to all connected clients
*/
socket.on("newUser", function(data){
participants.push({id: data.id, name: data.name});
console.log("newUser: ", data.name);
io.sockets.emit("newConnection", {participants: participants});
});
/**
* When a user changes his name, we are expecting an event called "nameChange",
* and then we'll emit an event called "nameChanged" to all participants with the id and new name of the user who emitted the original message
*/
socket.on("nameChange", function (data) {
console.log("nameChange: ", _findWhere(participants, {id: socket.id}).name, data.name);
_.findWhere(participants, {id: socket.id}).name = data.name;
io.sockets.emit("nameChanged", {id: data.id, name: data.name});
});
/**
* When a client disconnects from the server, the event "disconnect" is automatically captured by the server. It will then emit an event called "userDisconnected" to all participants with the id of the client that disconnected
*/
socket.on("disconnect", function () {
participants = _.without(participants, _.findWhere(participants, {id: socket.id})
);
io.sockets.emit("userDisconnected", {
id: socket.id,
sender: "system"
});
});
});
//Start the http server at port and IP defined before
http.listen(app.get("port"), app.get("ipaddr"), function() {
console.log("Server up and running. Go to http://" + app.get("ipaddr") + ":" + app.get("port"));
});
index.js:
function init () {
var serverBaseUrl = document.domain;
/**
* ON client init, try to connect to the socket.IO server.
* Note we don't specify a port since we set up our server to run on port 8080
*/
var socket = io.connect(serverBaseUrl);
// We'll save our session ID in a variable for later
var sessionId = '';
//Helper function to update the participants' list
function updateParticipants(participants) {
$('#participants').html('');
for (var i = 0; i < participants.length; i++) {
$('#participants').append('<span id="' + participants[i].id + '">' + participants[i].name + ' ' + (participants[i].id === sessionId ? '(You)' : '') + '<br /></span>');
}
}
/**
* When the client successfully connects to the server, an event "connect" is emitted. Let's get the session ID and log it.
* Also, let the socket.IO server know there's a new user with a session ID and a name. We'll emit the "newUser" event for that.
*/
socket.on("connect", function(){
sessionId = socket.io.engine.id;
console.log("Connected " + sessionId);
socket.emit("newUser", {
id: sessionId,
name: $("#name").val()
});
});
/**
* When the server emits the "newConnection" event, we'll reset the participants section and display the connected clients. Note we are assigning the sessionId as the span ID.
*/
socket.on("newConnection", function(data){
updateParticipants(data.participants);
});
/**
* When the server emits the "userDisconnected" event, we'll remove the span element from the participants element
*/
socket.on("userDisconnected", function (data) {
$("#"+data.id).remove();
});
/**
* When the server fires the "nameChanged" event, it means we must update the span with the given ID accordingly
*/
socket.on("nameChanged", function (data) {
$("#"+data.id).html(data.name + " " + (data.id === sessionId ? "(You)" : "") + "<br />");
});
/**
* When receiving a new chat message with the "incomingMessage" event, we'll prepend it to the messages section
*/
socket.on("incomingMessage", function (data) {
console.log("incomingMessage", data);
var msg = data.message;
var name = data.name;
$("#messages").prepend("<b>"+name+"</b><br/>" + message + "<hr />");
});
/**
* Log an error if unable to connect to server
*/
socket.on("error", function (reason) {
console.log("Unable to connect to server", reason);
});
/**
* "sendMessage" will do a simple ajax POST call to our server with whatever message we have in our textarea
*/
function sendMessage () {
var outgoingMessage = $("#outgoingMessage").val();
var name = $("#name").val();
$.ajax({
url: "/message",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({
message: outgoingMessage,
name: name
})
});
}
/**
* If user presses Enter key on textarea, call sendMessage if there is something to share
*/
function outgoingMessageKeyDown (event) {
if(event.which == 13){
event.preventDefault();
if($("#outgoingMessage").val().trim().length <= 0){
return;
}
sendMessage();
$("#outgoingMessage").val("");
}
}
/**
* Helper function to disable/enable Send button
*/
function outgoingMessageKeyUp(){
var outgoingMessageValue = $("#outgoingMessage").val();
$("#send").attr("disabled", (outgoingMessageValue.trim()).length > 0 ? false : true
);
}
/**
* When a user updates his/her name, let the server know by emitting the "nameChange" event
*/
function nameFocusOut () {
var name = $("#name").val();
socket.emit("nameChange", {
id: sessionId,
name: name
});
}
/**
* Elements setup
*/
$("#outgoingMessage").on("keydown", outgoingMessageKeyDown);
$("#outgoingMessage").on("keyup", outgoingMessageKeyUp);
$("#name").on("focusout", nameFocusOut);
$("#send").on("click", sendMessage);
// For debugging
debo.socket = socket;
}
window.debo = {};
$(document).on('ready', init);
答案 0 :(得分:1)
问题在于你在index.js中处理“incomingMessage”事件。您正在尝试解析未定义的“消息”值,而不是解析“msg”的值。因此,您会收到“解析器解码错误”。将两个变量更改为“msg”或“message”,您将不再收到错误。
socket.on("incomingMessage", function (data) {
console.log("incomingMessage", data);
var msg = data.message;
var name = data.name;
// "message" is undefined, you meant to read "msg"
$("#messages").prepend("<b>"+name+"</b><br/>" + message + "<hr />");
});
将其更改为:
socket.on("incomingMessage", function (data) {
console.log("incomingMessage", data);
var message = data.message;
var name = data.name;
$("#messages").prepend("<b>"+name+"</b><br/>" + message + "<hr />");
});