我有这个网络TCP服务器:
private startTCPServer() {
const socket = net.createServer(function(socket_object){
socket_object.on("data", (data) => {
console.log(data);
});
socket_object.on("end", socket_object.end);
socket_object.on("error", (err: any) => {
console.log(err);
});
});
socket.listen(this.TCP_PORT, this.ADDRESS, () => {
console.log('listening...');
});
}
如何在达到"data"
事件时获取连接到此服务器的客户端的IP?
答案 0 :(得分:2)
您的connectListener
(授予createServer
的功能)获取socket_object
,它是net.Socket
类型的对象。有一个属性remoteAddress
,它具有远程主机的地址。
答案 1 :(得分:0)
为了补充,例如,如果你想在remoteAddress
事件中使用"data"
,请执行以下操作:
private startTCPServer() {
const wrapper = (remoteAddress: string) => {
return (data: any) => {
console.log(data, remoteAddress);
}
};
const socket = net.createServer(function(socket_object){
socket_object.on("data", wrapper(socket_object.remoteAddress));
socket_object.on("end", socket_object.end);
socket_object.on("error", (err: any) => {
console.log(err);
});
});
socket.listen(this.TCP_PORT, this.ADDRESS, () => {
console.log('listening...');
});
}