index.html 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <html>
  2. <title>测试</title>
  3. <style>
  4. *{
  5. margin:0;
  6. padding:0;
  7. }
  8. .meta{
  9. width:500px;
  10. height:800px;
  11. border-radius: 5%;
  12. border:3px solid #000;
  13. margin:10px auto;
  14. position:relative;
  15. }
  16. .login_info{
  17. width:100%;
  18. height:40px;
  19. border-bottom:3px solid #000;
  20. position:absolute;
  21. left:0;
  22. top:0;
  23. line-height:40px;
  24. text-align:center;
  25. display:none;
  26. }
  27. </style>
  28. <body>
  29. <div class="meta">
  30. <div class="login_info">
  31. </div>
  32. </div>
  33. <script type="text/javascript">
  34. if (typeof console == "undefined") {
  35. this.console = {
  36. log: function (msg) {}
  37. };
  38. }
  39. var ws, name, client_list={};
  40. function connect(){
  41. // 创建websocket
  42. ws = new WebSocket("ws://127.0.0.1:2346");
  43. // 当socket连接打开时,输入用户名
  44. ws.onopen = onopen;
  45. // 当有消息时根据消息类型显示不同信息
  46. ws.onmessage = onmessage;
  47. ws.onclose = function() {
  48. console.log("连接关闭,定时重连");
  49. connect();
  50. };
  51. ws.onerror = function() {
  52. console.log("出现错误");
  53. };
  54. }
  55. // 连接建立时发送登录信息
  56. function onopen()
  57. {
  58. if(!name)
  59. {
  60. name = prompt('输入你的名字:', '');
  61. if(!name || name=='null'){
  62. name = '游客';
  63. }
  64. }
  65. var login_data = '{"type":"login","client_name":"'+name.replace(/"/g, '\\"')+'","room_id":"房间1"}';
  66. console.log(login_data);
  67. ws.send(login_data);
  68. }
  69. // 服务端发来消息时
  70. function onmessage(e)
  71. {
  72. var data = eval("("+e.data+")");
  73. switch(data['type']){
  74. // 服务端ping客户端
  75. case 'ping':
  76. ws.send('{"type":"pong"}');
  77. break;;
  78. // 登录 更新用户列表
  79. case 'login':
  80. alert(data['data']);
  81. }
  82. }
  83. connect();
  84. </script>
  85. </body>
  86. </html>