如何在为Node.JS编写的TCP服务器中实现类似于HTTP Basic身份验证的功能?基本TCP服务器的代码如下:
// Load the net module to create a tcp server.
var net = require('net');
// Setup a tcp server
var server = net.createServer(function (socket) {
// Every time someone connects, tell them hello and then close the connection.
socket.addListener("connect", function () {
console.log("Connection from " + socket.remoteAddress);
socket.end("Hello World\n");
});
});
// Fire up the server bound to port 7000 on localhost
server.listen(7000, "localhost");
// Put a friendly message on the terminal
console.log("TCP server listening on port 7000 at localhost.");
答案 0 :(得分:5)
虽然有几种方法可以通过TCP连接提供身份验证,但都需要某种形式的“协议”作为商定的通信语法/语法。
例如,在简单邮件传输协议中,会发生以下对话(其中S:和C:分别指定由SMTP服务器和电子邮件客户端提供的行):
S: 220 server.example.com
C: HELO client.example.com
S: 250 server.example.com
C: MAIL FROM:<sender@example.com>
S: 250 2.1.0 sender@example.com... Sender ok
C: RCPT TO:<recipient@example.com>
S: 250 recipient <recipient@example.com> OK
C: DATA
S: 354 enter mail, end with line containing only "."
C: full email message appears here, where any line
C: containing a single period is sent as two periods
C: to differentiate it from the "end of message" marker
C: .
S: 250 message sent
C: QUIT
S: 221 goodbye
在来自服务器的回复中,初始数值表示所请求操作的成功或失败,或者回复包含信息性消息。使用三位数字值可以进行有效的解析,因为以2xx开头的所有回复都表示成功,3xx是信息性的,4xx表示协议错误,5xx是为服务器错误保留的。有关完整协议,请参阅IETF RFC 5321 - http://tools.ietf.org/html/rfc5321。
因此,在您的具体情况下,您可能会考虑一些简单的事情:
[connect to TCP server]
S: ? # indicates the server is ready for authorization
C: username password # send authentication credentials
然后服务器将回复:
S: ! # indicates successful authentication and
# that server is ready for more commands
或者
S: ? # indicates authentication failure
如果看到太多失败的身份验证尝试,服务器可能会断开连接以减少滥用的可能性,例如DDOS攻击。
经过身份验证后,客户端可以发送:
C: > # begin streaming
或您支持的任何其他命令。