【发布时间】:2016-09-10 18:54:24
【问题描述】:
我正在使用 socket.io-client 和 socket.io 在终端中制作一个小型加密聊天应用程序。客户端能够连接到服务器,但在输入用户名时不会发出用户名。
客户:
var socket = require('socket.io-client')('http://127.0.0.1:3000');
socket.on('connect_error', function(){
console.log('Failed to establish a connection to the servers, or lost connection');
return process.exit();
});
var prompt = require("prompt-sync")()
var news = "Add news: Will be from database. "
var username = prompt("Username>: ")
console.log("Hold on a sec, just checking that!")
console.log("")
if (typeof username === "defined"){
socket.emit('user-name', {usr: 'username'})
}
socket.on('user-name-good',function(socket){
console.log("Okay! Your username looks good, we just require your password")
console.log("If you chose to have no password, please press enter with out pressing space!")
var password = prompt("Password>: ")
if (typeof password !== "defined"){
console.log("Please provide a password!")
return password = prompt("Username>: ")
}
socket.on('user-name-fail',function(socket){
console.log("Sorry, we could not find, "+username+""+"Please register on the website, or, if you have registered ")
return process.exit()
})
}
)
服务器代码,基于 socket.io 聊天示例中的代码:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
我添加了一个错误事件,如果与服务器的连接失败,这将关闭客户端,所以我知道它的连接,感谢任何帮助,我已经对此主题进行了研究,并尝试了很多其他方法,但是没用。
另外,连接是在您提交数据后建立的,而不是在客户端代码启动时建立的,这可能是什么原因造成的?
【问题讨论】:
标签: javascript node.js sockets socket.io