今天给聊天程序升个级 

局域网 多台机器 使用inde.html  发送消息 并显示 (就是群聊) 带着IP

socket.io 获得客户端IP 返回值是::ffff:IP 需要处理一下 用js replace('::ffff:', ''); 处理一下 完事

if(socket.handshake.headers['x-forwarded-for'] != null){
ip = socket.handshake.headers['x-forwarded-for'];
}else{
ip = socket.handshake.address;
}

nodejs

var http = require('http');//http模块加载
var fs = require('fs');//文件模块加载
var url=require("url");

var server = http.createServer(function(request,response)
{
if(url.parse(request.url).path=='/favicon.ico')
return;
fs.readFile(__dirname+'/index.html',function(err,data)
{
if(err)
{
console.log(err);
}else
{
response.writeHead(200, {'Content-Type': 'text/plain;charset=UTF8'});
response.write(data);
response.end();
}
});
}).listen(8888);
//实例化上面的链接 server
var io = require('socket.io')(server);
io.on('connection',function(socket)
{
var ip='';
// socket.on('sendMessage',function(data)
// {

// })
if(socket.handshake.headers['x-forwarded-for'] != null){
ip = socket.handshake.headers['x-forwarded-for'];
}else{
ip = socket.handshake.address;
}
socket.on('sendMessage', (data) => {
data.id = socket.id;

data.msg= ip+':' +data.msg;
data.msg = data.msg.replace('::ffff:', '');
console.log(data.msg);
//调用客户端事件
io.emit('receiveMessage', data);
})
}
);

HTML

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>群聊</title>
</head>
<body>
<h1>群聊</h1>
<div style="width: 30%; float: left">
输入:<input type="text" id="msginput">
<button id="msgbtn">发送</button>
</div>
<div style="width: 65%; float: right" id="showbox">

</div>
</body>
<script src="http://Nodejs服务IP:端口号/socket.io/socket.io.js">
// 这个script标签访问数据就相当访问了127.0.0.1:3000/socket.io/socket.io.js,浏览器打开其实就是socket.io插件源码
</script>
<script>
let socket = io.connect('http://Nodejs服务IP:端口号');
let btn = document.getElementById('msgbtn');
let msginput = document.getElementById('msginput');
let showbox = document.getElementById('showbox');
btn.addEventListener('click', (event) => {
let msg = msginput.value;
let data = {msg: msg};
//服务器声明好的事件
socket.emit('sendMessage', data);
});
//服务器socket 调用的receiveMessage事件
socket.on('receiveMessage', (data) => {
console.log('收到');
console.log(data);

let message = document.createElement('div');
message.innerHTML = `${data.msg}`;
showbox.appendChild(message);
});
</script>

</html>

Nodejs(socket.io获得访问IP)_html

隐藏一下IP 虽然不知道会怎么样 但是还是涂上的好

Nodejs(socket.io获得访问IP)_服务器_02