client.html 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <html>
  2. <head>
  3. <title>Golang Chat</title>
  4. <script src="http://libs.baidu.com/jquery/1.4.2/jquery.min.js"></script>
  5. <meta charset="UTF-8" />
  6. <script type="text/javascript">
  7. $(function() {
  8. function getUrlParam(name)
  9. {
  10. var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  11. var r = window.location.search.substr(1).match(reg); //匹配目标参数
  12. if (r!=null) return unescape(r[2]); return null; //返回参数值
  13. }
  14. var conn;
  15. var msg = $("#msg");
  16. var log = $("#log");
  17. uid=getUrlParam("uid");
  18. to_uid=getUrlParam("to_uid");
  19. function appendLog(msg) {
  20. var d = log[0]
  21. var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
  22. msg.appendTo(log)
  23. if (doScroll) {
  24. d.scrollTop = d.scrollHeight - d.clientHeight;
  25. }
  26. }
  27. $("#form").submit(function() {
  28. if (!conn) {
  29. return false;
  30. }
  31. if (!msg.val()) {
  32. return false;
  33. }
  34. var json = {"sender":uid,"recipient":to_uid,"content":msg.val()}; //创建对象;
  35. var jsonStr = JSON.stringify(json); //转为JSON字符串
  36. conn.send(jsonStr);
  37. msg.val("");
  38. return false
  39. });
  40. if (window["WebSocket"]) {
  41. conn = new WebSocket("ws://localhost:8000/ws?uid="+uid+"&to_uid="+to_uid);
  42. conn.onclose = function(evt) {
  43. appendLog($("<div><b>Connection Closed.</b></div>"))
  44. }
  45. conn.onmessage = function(evt) {
  46. appendLog($("<div/>").text(evt.data))
  47. }
  48. } else {
  49. appendLog($("<div><b>WebSockets Not Support.</b></div>"))
  50. }
  51. });
  52. </script>
  53. <style type="text/css">
  54. html {
  55. overflow: hidden;
  56. }
  57. body {
  58. overflow: hidden;
  59. padding: 0;
  60. margin: 0;
  61. width: 100%;
  62. height: 100%;
  63. background: gray;
  64. }
  65. #log {
  66. background: white;
  67. margin: 0;
  68. padding: 0.5em 0.5em 0.5em 0.5em;
  69. position: absolute;
  70. top: 0.5em;
  71. left: 0.5em;
  72. right: 0.5em;
  73. bottom: 3em;
  74. overflow: auto;
  75. }
  76. #form {
  77. padding: 0 0.5em 0 0.5em;
  78. margin: 0;
  79. position: absolute;
  80. bottom: 1em;
  81. left: 0px;
  82. width: 100%;
  83. overflow: hidden;
  84. }
  85. </style>
  86. </head>
  87. <body>
  88. <div id="log"></div>
  89. <form id="form">
  90. <input type="submit" value="发送" />
  91. <input type="text" id="msg" size="64"/>
  92. </form>
  93. </body>
  94. </html>