我是nodeJS的新成员。我有一台服务器从客户端接收命令。它向服务器发送名为" TIME"的命令。然后服务器必须向客户端发送当前时间戳。一旦客户端从服务器收到时间戳,第一个发送另一个命令。
我不知道自己做错了什么。我收到了" TIME"命令但是当服务器向客户端发送当前时间戳时,它不会从客户端接收响应。这可能是一个客户问题。我想知道下面写的代码是否正确。
var net = require("net");
net.createServer(function(socket) {
console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
socket.on('data', function(data) {
var tmp = data.toString('utf8');
var d = new Date();
if (tmp.substr(0, 4) == "TIME"){
console.log(buffer.toString('utf8'));
var ts = Math.round((new Date()).getTime() / 1000);
socket.write(ts.toString() + "\n");
}else if (tmp.substr(19, 3)== "PW:"){
console.log("PW packet received with UID="+tmp.substr(6, 18)+" and len="+tmp.substr(22, 27));
socket.write("ODEOK\n\r");
}else if (tmp.substr(19, 3)== "ST:"){
console.log("ST packet received with UID="+tmp.substr(6, 18)+" and len="+tmp.substr(22, 27));
socket.write("ODEOK\n\r");
}else{
console.log("Unknown data:"+ data);
socket.write("ODERR\n\r");
}
});
socket.on('close', function(data) {
console.log('CLOSED: ' + socket.remoteAddress +' '+ socket.remotePort);
});
socket.on('end', function() {
console.log('client disconnected');
});}).listen(1730);
我用python测试了它,它的工作原理。我不知道为什么。
#!/usr/bin/python
import socket
import time
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("0.0.0.0", 1730))
s.listen(10)
while True:
sc, addr = s.accept()
data = sc.recv(1024)
if data[0:4] == "TIME":
print "TIME command received"
sc.send(str(int(time.time()))+"\n")
elif data[19:22] == "PW:":
print "PW packet received with UID="+data[6:18]+" and len="+data[22:27]
sc.send("ODEOK\n")
elif data[19:22] == "SG:":
print "SG packet received with UID="+data[6:18]+" and len="+data[22:27]
sc.send("ODEOK\n")
elif data[19:22] == "ST:":
print "ST packet received with UID="+data[6:18]+" and len="+data[22:27]
sc.send("ODEOK\n")
else:
print "Unknown data:", data
sc.send("ODERR\n")
sc.close()
s.close()