chat.html 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. <!DOCTYPE HTML>
  2. <html lang="en">
  3. <head>
  4. <title>PeerJS chat demo</title>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  6. <meta http-equiv="Content-Language" content="en-us">
  7. <link href="fancy.css" rel="stylesheet" type="text/css">
  8. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
  9. <script type="text/javascript" src="../dist/peer.js"></script>
  10. <script>
  11. // Connect to PeerJS, have server assign an ID instead of providing one
  12. // Showing off some of the configs available with PeerJS :).
  13. var peer = new Peer({
  14. // Set API key for cloud server (you don't need this if you're running your
  15. // own.
  16. key: 'x7fwx2kavpy6tj4i',
  17. // Set highest debug level (log everything!).
  18. debug: 3,
  19. // Set a logging function:
  20. logFunction: function() {
  21. var copy = Array.prototype.slice.call(arguments).join(' ');
  22. $('.log').append(copy + '<br>');
  23. }
  24. });
  25. var connectedPeers = {};
  26. // Show this peer's ID.
  27. peer.on('open', function(id){
  28. $('#pid').text(id);
  29. });
  30. // Await connections from others
  31. peer.on('connection', connect);
  32. peer.on('error', function(err) {
  33. console.log(err);
  34. })
  35. // Handle a connection object.
  36. function connect(c) {
  37. // Handle a chat connection.
  38. if (c.label === 'chat') {
  39. var chatbox = $('<div></div>').addClass('connection').addClass('active').attr('id', c.peer);
  40. var header = $('<h1></h1>').html('Chat with <strong>' + c.peer + '</strong>');
  41. var messages = $('<div><em>Peer connected.</em></div>').addClass('messages');
  42. chatbox.append(header);
  43. chatbox.append(messages);
  44. // Select connection handler.
  45. chatbox.on('click', function() {
  46. if ($(this).attr('class').indexOf('active') === -1) {
  47. $(this).addClass('active');
  48. } else {
  49. $(this).removeClass('active');
  50. }
  51. });
  52. $('.filler').hide();
  53. $('#connections').append(chatbox);
  54. // Just to fix the connection receiver to successfully send a message to the connection requester
  55. c.open = true;
  56. c.on('data', function(data) {
  57. messages.append('<div><span class="peer">' + c.peer + '</span>: ' + data +
  58. '</div>');
  59. });
  60. c.on('close', function() {
  61. alert(c.peer + ' has left the chat.');
  62. chatbox.remove();
  63. if ($('.connection').length === 0) {
  64. $('.filler').show();
  65. }
  66. delete connectedPeers[c.peer];
  67. });
  68. } else if (c.label === 'file') {
  69. c.on('data', function(data) {
  70. // If we're getting a file, create a URL for it.
  71. if (data.constructor === ArrayBuffer) {
  72. var dataView = new Uint8Array(data);
  73. var dataBlob = new Blob([dataView]);
  74. var url = window.URL.createObjectURL(dataBlob);
  75. $('#' + c.peer).find('.messages').append('<div><span class="file">' +
  76. c.peer + ' has sent you a <a target="_blank" href="' + url + '">file</a>.</span></div>');
  77. }
  78. });
  79. }
  80. connectedPeers[c.peer] = 1;
  81. }
  82. $(document).ready(function() {
  83. // Prepare file drop box.
  84. var box = $('#box');
  85. box.on('dragenter', doNothing);
  86. box.on('dragover', doNothing);
  87. box.on('drop', function(e){
  88. e.originalEvent.preventDefault();
  89. var file = e.originalEvent.dataTransfer.files[0];
  90. eachActiveConnection(function(c, $c) {
  91. if (c.label === 'file') {
  92. c.send(file);
  93. $c.find('.messages').append('<div><span class="file">You sent a file.</span></div>');
  94. }
  95. });
  96. });
  97. function doNothing(e){
  98. e.preventDefault();
  99. e.stopPropagation();
  100. }
  101. // Connect to a peer
  102. $('#connect').click(function() {
  103. var requestedPeer = $('#rid').val();
  104. if (!connectedPeers[requestedPeer]) {
  105. // Create 2 connections, one labelled chat and another labelled file.
  106. var c = peer.connect(requestedPeer, {
  107. label: 'chat',
  108. serialization: 'none',
  109. metadata: {message: 'hi i want to chat with you!'}
  110. });
  111. c.on('open', function() {
  112. connect(c);
  113. });
  114. c.on('error', function(err) { alert(err); });
  115. var f = peer.connect(requestedPeer, { label: 'file', reliable: true });
  116. f.on('open', function() {
  117. connect(f);
  118. });
  119. f.on('error', function(err) { alert(err); });
  120. }
  121. connectedPeers[requestedPeer] = 1;
  122. });
  123. // Close a connection.
  124. $('#close').click(function() {
  125. eachActiveConnection(function(c) {
  126. c.close();
  127. });
  128. });
  129. // Send a chat message to all active connections.
  130. $('#send').submit(function(e) {
  131. e.preventDefault();
  132. // For each active connection, send the message.
  133. var msg = $('#text').val();
  134. eachActiveConnection(function(c, $c) {
  135. if (c.label === 'chat') {
  136. c.send(msg);
  137. $c.find('.messages').append('<div><span class="you">You: </span>' + msg
  138. + '</div>');
  139. }
  140. });
  141. $('#text').val('');
  142. $('#text').focus();
  143. });
  144. // Goes through each active peer and calls FN on its connections.
  145. function eachActiveConnection(fn) {
  146. var actives = $('.active');
  147. var checkedIds = {};
  148. actives.each(function() {
  149. var peerId = $(this).attr('id');
  150. if (!checkedIds[peerId]) {
  151. var conns = peer.connections[peerId];
  152. for (var i = 0, ii = conns.length; i < ii; i += 1) {
  153. var conn = conns[i];
  154. fn(conn, $(this));
  155. }
  156. }
  157. checkedIds[peerId] = 1;
  158. });
  159. }
  160. // Show browser version
  161. $('#browsers').text(navigator.userAgent);
  162. });
  163. // Make sure things clean up properly.
  164. window.onunload = window.onbeforeunload = function(e) {
  165. if (!!peer && !peer.destroyed) {
  166. peer.destroy();
  167. }
  168. };
  169. </script>
  170. </head>
  171. <body>
  172. <a href="https://github.com/peers/peerjs"><img style="position: absolute; top: 0; right: 0; border: 0;"
  173. src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png"
  174. alt="Fork me on GitHub"></a>
  175. <div id="actions">
  176. Your PeerJS ID is <span id="pid"></span><br>
  177. Connect to a peer: <input type="text" id="rid" placeholder="Someone else's id"><input class="button" type="button" value="Connect" id="connect"><br><br>
  178. <form id="send">
  179. <input type="text" id="text" placeholder="Enter message"><input class="button" type="submit" value="Send to selected peers">
  180. </form>
  181. <button id="close">Close selected connections</button>
  182. </div>
  183. <div id="wrap"><div id="connections"><span class="filler">You have not yet
  184. made any connections.</span></div>
  185. <div class="clear"></div></div>
  186. <div id="box" style="background: #fff; font-size: 18px;padding:40px 30px; text-align: center;">
  187. Drag file here to send to active connections.
  188. </div>
  189. <div class="warning browser">
  190. <div class="important">Your browser version: <span id="browsers"></span><br>
  191. Currently <strong>Firefox 22+ and Google Chrome 26.0.1403.0 or above</strong> is required.</strong></div>For more up to date compatibility
  192. information see <a href="http://peerjs.com/status">PeerJS WebRTC
  193. Status</a><br>Note that this demo may also fail if you are behind
  194. stringent firewalls or both you and the remote peer are behind symmetric
  195. NATs.
  196. <div class="log" style="color:#FF7500;text-shadow:none;padding:15px;background:#eee"><strong>Connection status</strong>:<br></div>
  197. </div>
  198. </body>
  199. </html>