//客户端---------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>实时通讯</h1>
<textarea cols="50" id="content" rows="10"></textarea>
<br>
<input type="text" id="msg" >
<input type="submit" value="提交" id="btn">
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io("http://localhost:3000");
var btn = document.getElementById("btn");
var msg = document.getElementById("msg");
var content = document.getElementById("content");
var user = "tempUser"+ Math.floor(Math.random()*1000);
btn.onclick = ()=>{
var str = msg.value;
socket.emit("sendMsg",user +":"+str);
}
socket.on("myNews",(msg)=>{
console.log("msg",msg);
content.value += msg +"\n";
})
</script>
</body>
</html>
//服务器端---------------------------
var http = require("http");
var fs = require("fs");
var io = require("socket.io");
var server = http.createServer((req,res)=>{
if(req.url=="/"){
fs.readFile("index.html",(err,data)=>{
res.end(data);
})
}else {
res.end("no page found");
}
})
server.listen(3000);
var ioClass = require("socket.io");
var ioInstanct = ioClass(server);
ioInstanct.on("connection",(socket)=>{
socket.on("sendMsg",(data)=>{
console.log("dada:",data);
ioInstanct.emit("myNews","服务器转发:"+data);
});
})