我想把客户端的代码放入到php中,因为我如果完成一个聊天,可能会有如下场景:用php开发一个商城,里面有个和商户聊天的场景,node代码我不变,只希望客户端的前端代码嵌入到php渲染的模板中。
我们新建一个php文件在同一个目录,叫index.php。并把客户端代码拷贝到里面:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
<html> <head> <title>Socket.IO chat</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> </head> <body> <ul id="messages"></ul> <form action=""> <select id="suser"> </select> <input type="hidden" id="selfname" /> <input id="m" autocomplete="off" /><button>Send</button> </form> </body> <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.js"></script> <script> var socket = io("http://127.0.0.1:3000"); //生成随机数 sjMath= Math.floor(Math.random()*10000); $('#selfname').val(sjMath); //将随机数用户名发送到客户端 socket.emit('add user', sjMath); socket.on('get user', function(msg){ $('#messages').append($('<li>').text("欢迎"+msg+"加入")); }); //获取所有服务器发来的用户名 socket.on('get alluser', function(msg){ $('#suser').empty(); $('#suser').append("<option value='0'>群聊</option>"); for ( var p in msg ) { $('#suser').append("<option value="+msg[p]+">"+msg[p]+"</option>"); } }); $('form').submit(function(){ // alert($('#selfname').val(msg)+ $('suser').val()); socket.emit('chat message', $('#m').val(),$('#selfname').val(),$('#suser').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); //接收别人发来的信息 socket.on('to '+$('#selfname').val(), function(msg){ $('#messages').append($('<li>').text(msg)); }); //我给别人发的信息 socket.on('send '+$('#selfname').val(), function(msg){ $('#messages').append($('<li>').text(msg)); }); </script> <?php echo "这是php文件"; ?> </html> |
这里着注意的是我修改了var socket = io(“http://127.0.0.1:3000″);
因为iis指定到我们的inde.php后,浏览器访问php输入的url和端口号发生了改变,已经和node服务器端的url和端口不一样了。
你需要让你的php页面能够访问到node监听的服务。