Advertisement
Guest User

Untitled

a guest
Feb 4th, 2016
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.29 KB | None | 0 0
  1. <title> Chat</title>
  2.  
  3. <link rel="stylesheet" type="text/css" href="Bootstrap/chat.css" />
  4.  
  5. <script src="Bootstrap/jquery.js"></script>
  6.  
  7. <style type="text/css">
  8.  
  9.  
  10. input#chat {
  11. width: 410px
  12. }
  13.  
  14. #console-container {
  15. width: 400px;
  16. }
  17.  
  18. #console {
  19. border: 1px solid #CCCCCC;
  20. border-right-color: #999999;
  21. border-bottom-color: #999999;
  22. height: 170px;
  23. overflow-y: scroll;
  24. padding: 5px;
  25. width: 100%;
  26. }
  27.  
  28. #console p {
  29. padding: 0;
  30. margin: 0;
  31. }
  32. </style>
  33.  
  34. var host = window.location.host;
  35. var path = window.location.pathname;
  36. var webCtx = path.substring(0, path.indexOf('/', 1));
  37. var endPointURL = "ws://" + window.location.host + webCtx + "/user /chatonline";
  38.  
  39. var Chat = {};
  40. var windows_ass = {};
  41. var message_holder = {};
  42.  
  43. Chat.socket = null;
  44.  
  45. Chat.connect = (function(host) {
  46. if ('WebSocket' in window) {
  47. Chat.socket = new WebSocket(host);
  48. } else if ('MozWebSocket' in window) {
  49. Chat.socket = new MozWebSocket(host);
  50. } else {
  51. alert("Some thing went wrong!!");
  52. return;
  53. }
  54.  
  55. Chat.socket.onopen = function () {
  56. // var to = $(this).attr('data-to');
  57. // alert(to);
  58. $('.message' ).keydown(function(event) {
  59.  
  60. if (event.keyCode == 13) {
  61. var mto = $(this).attr('data-to');
  62. // alert(mto);
  63. var text = $(this).val();
  64. sendMessage(mto,text);
  65. $(this).prev().append("<div class='data-msg send' style='margin-top:7px;float:right;color:#fff;background-color:#3b94d9;clear:both;' >" + text + " <div class='dm-caret'><div class='dm-caret-outer'></div><div class='dm-caret-inner'></div></div> </div> <br/>");
  66. $(this).val('');
  67. }
  68.  
  69. });
  70. };
  71.  
  72. Chat.socket.onclose = function () {
  73. document.getElementById('chat').onkeydown = null;
  74.  
  75. };
  76.  
  77. Chat.socket.onmessage = function (event) {
  78. var div = document.getElementById('online');
  79.  
  80. var message = JSON.parse(event.data);
  81.  
  82. if(message.action == 'connected'){
  83.  
  84. div.innerHTML = div.innerHTML + "<li id='"+message.name+"' > <div class='chch-userAvatarWrapper'> <div class='chch-emptyAvatar chch-circularAvatar'><svg class='chch-emptyAvatarIco' enable-background='new 0 0 50 50' id='Layer_1' version='1.1' viewBox='0 0 50 50' xml:space='preserve' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><rect fill='none' height='50' width='50'></rect><path d='M30.933,32.528c-0.146-1.612-0.09-2.737-0.09-4.21c0.73-0.383,2.038-2.825,2.259-4.888c0.574-0.047,1.479-0.607,1.744-2.818 c0.143-1.187-0.425-1.855-0.771-2.065c0.934-2.809,2.874-11.499-3.588-12.397c-0.665-1.168-2.368-1.759-4.581-1.759 c-8.854,0.163-9.922,6.686-7.981,14.156c-0.345,0.21-0.913,0.878-0.771,2.065c0.266,2.211,1.17,2.771,1.744,2.818 c0.22,2.062,1.58,4.505,2.312,4.888c0,1.473,0.055,2.598-0.091,4.21C19.367,37.238,7.546,35.916,7,45h38 C44.455,35.916,32.685,37.238,30.933,32.528z'></path></svg></div> </div> <span>"+ message.name +" </span> <i> </i> </li>";
  85. }
  86. if(message.action == 'disconnected')
  87. {
  88.  
  89. var to_remove = document.getElementById(message.name);
  90. to_remove.remove();
  91.  
  92. }
  93.  
  94. if(message.action == 'frndmessage'){
  95.  
  96.  
  97. if(windows_ass[message.from] !== undefined )
  98. {
  99.  
  100. $('.'+windows_ass[message.from]+ ' .content').append("<div class='data-msg rec' style='margin-top:7px;float:left;color:#fff;background-color:#3b94d9;clear:both;' >" + message.message + " <div class='dm-caretf'><div class='dm-caret-outer'></div><div class='dm-caret-inner'></div></div> </div> <br/>");
  101.  
  102. }else{
  103.  
  104. if(message_holder[message.from] === undefined)
  105. {
  106. message_holder[message.from] = [];
  107. }
  108. var fr = message.from;
  109. message_holder[fr].push(message.message);
  110.  
  111. $('#'+message.from+ ' i').html(message_holder[fr].length);
  112. }
  113. }
  114.  
  115. };
  116. });
  117.  
  118. Chat.initialize = function() {
  119. //var name = getParameterByName('name');
  120. if (window.location.protocol == 'http:') {
  121. Chat.connect(endPointURL);
  122. } else {
  123. Chat.connect(endPointURL);
  124. }
  125. };
  126.  
  127. function sendMessage(mto,message){
  128.  
  129.  
  130. var information = {
  131. action: "Message",
  132. to: mto,
  133. message: message
  134. };
  135.  
  136.  
  137. if (message != '') {
  138. Chat.socket.send(JSON.stringify(information));
  139.  
  140. }
  141. }
  142.  
  143. Chat.initialize();
  144. document.addEventListener("DOMContentLoaded", function() {
  145. // Remove elements with "noscript" class - <noscript> is not allowed in XHTML
  146. var noscripts = document.getElementsByClassName("noscript");
  147. for (var i = 0; i < noscripts.length; i++) {
  148. noscripts[i].parentNode.removeChild(noscripts[i]);
  149. }
  150. }, false);
  151.  
  152. </script>
  153.  
  154. <h2>Chat Using WebSockets: Tomcat server</h2>
  155.  
  156.  
  157. <div id="online">
  158.  
  159.  
  160.  
  161. </div>
  162.  
  163.  
  164. <div class="window1">
  165. <div class="header">
  166. <div style="float:left;margin-left: 9px;color: white;margin-top: 3px" class="from"></div>
  167. <svg style="float:right" version="1.2" baseProfile="tiny" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
  168. x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24" xml:space="preserve"></svg>
  169.  
  170. </div>
  171. <div class="content"> </div>
  172. <input type="text" class="message" style="width: 272px;height: 30px;" data-to="" />
  173. </div>
  174.  
  175.  
  176. <div class="window2">
  177. <div class="header">
  178. <div style="float:left;margin-left: 9px;color: white;margin-top: 3px" class="from"></div>
  179.  
  180. <svg style="float:right" version="1.2" baseProfile="tiny" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
  181. x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24" xml:space="preserve"></svg>
  182.  
  183. </div>
  184. <div class="content"> </div>
  185. <input type="text" class="message" style="width: 272px;height: 30px;" data-to="" />
  186. </div>
  187.  
  188.  
  189. <div class="window3">
  190. <div class="header">
  191. <div style="float:left;margin-left: 9px;color: white;margin-top: 3px" class="from"></div>
  192.  
  193. <svg style="float:right" version="1.2" baseProfile="tiny" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
  194. x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24" xml:space="preserve">
  195.  
  196.  
  197.  
  198. </div>
  199.  
  200.  
  201. <div class="content"> </div>
  202. <input type="text" class="message" style="width: 272px;height: 30px;" data-to="" />
  203. </div>
  204.  
  205. <script>
  206.  
  207.  
  208.  
  209. var windows = [] ;
  210.  
  211. $( "body" ).on( 'click', '#online li', function (){
  212.  
  213.  
  214.  
  215. var mesg_to = $(this).attr('id');
  216.  
  217. if( windows.indexOf("window1") === -1){
  218.  
  219. windows_ass[mesg_to] = "window1";
  220. windows.push("window1");
  221. $(".window1").show();
  222. $(".window1 .from").text(mesg_to);
  223. $('.window1 input').attr( 'data-to', mesg_to);
  224.  
  225. if(message_holder[mesg_to] !== undefined)
  226. {
  227. var lengt = message_holder[mesg_to].length;
  228. for (var i = 0; i<lengt; i++) {
  229.  
  230.  
  231. $('.window1 .content').append("<div class='data-msg rec' style='margin-top:7px;float:left;color:#fff;background-color:#3b94d9;clear:both;' >" + message_holder[mesg_to][i] + " <div class='dm-caretf'><div class='dm-caret-outer'></div><div class='dm-caret-inner'></div></div> </div> <br/>");
  232.  
  233.  
  234. }
  235.  
  236. }
  237.  
  238. }
  239. else if( windows.indexOf("window2") === -1 )
  240. {
  241.  
  242. windows_ass[mesg_to] = "window2";
  243. windows.push("window2");
  244. $(".window2").show();
  245. $(".window2 .from").text(mesg_to);
  246. $('.window2 input').attr( 'data-to', mesg_to);
  247.  
  248. }
  249. else {
  250.  
  251. windows_ass[mesg_to] = "window3";
  252. windows.push("window3");
  253. $(".window3").show();
  254. $(".window3 .from").text(mesg_to);
  255. $('.window3 input').attr( 'data-to', mesg_to);
  256.  
  257. }
  258.  
  259. });
  260.  
  261.  
  262. </script>
  263.  
  264. @Override
  265. public void modifyHandshake(ServerEndpointConfig sec,
  266. HandshakeRequest request,
  267. HandshakeResponse response)
  268. {
  269.  
  270. sec.getUserProperties().put("email",(String)((HttpSession)request.getHttpSession()).getAttribute("email"));
  271. }
  272.  
  273. private static final Log log = LogFactory.getLog(ChatWebsocket.class);
  274. static Map<String, Session> hm = new HashMap<String, Session>( );
  275.  
  276. private static final Set<ChatWebsocket> connections = new CopyOnWriteArraySet<ChatWebsocket>();
  277.  
  278. private String nickname;
  279. private Session session;
  280. private String to;
  281. JsonProvider provider = JsonProvider.provider();
  282. public ChatWebsocket() {
  283.  
  284.  
  285. }
  286.  
  287.  
  288. @OnOpen
  289. public void start(EndpointConfig config, Session session) {
  290. this.session = session;
  291. connections.add(this);
  292. nickname= (String) session.getUserProperties().put("email",config.getUserProperties().get("email"));
  293. //nickname = name;
  294. // if(nickname.equals(config.getUserProperties().get("email")))
  295.  
  296.  
  297. hm.put(nickname, session);
  298. JsonObject connected = provider.createObjectBuilder()
  299. .add("action", "connected")
  300. .add("name", nickname)
  301. .build();
  302.  
  303.  
  304. broadcast_all(connected);
  305. JSONObject obj = new JSONObject();
  306. obj.put("to",to);
  307. System.out.println(to);
  308. //let send about existing users.
  309. /*JsonReader reader=new JsonReader();
  310. JsonObject jsonMessage = reader.readObject();
  311. System.out.println("to:"+jsonMessage.getString("to"));*/
  312. for (Map.Entry<String, Session> entry : hm.entrySet()) {
  313.  
  314. if(entry.getKey().equals(nickname)){
  315. //System.out.println("double:"+entry.getKey());
  316. } else {
  317.  
  318. JsonObject conn = provider.createObjectBuilder()
  319. .add("action", "connected")
  320. .add("name",entry.getKey() )
  321. .build();
  322.  
  323. broadcastex(conn, nickname);
  324. }
  325. }
  326.  
  327. }
  328.  
  329.  
  330. @OnClose
  331. public void end() {
  332. connections.remove(this);
  333. JsonObject dis = provider.createObjectBuilder()
  334. .add("action", "disconnected")
  335. .add("name", nickname)
  336. .build();
  337. broadcast_all(dis);
  338. }
  339.  
  340.  
  341. @OnMessage
  342. public void incoming(String message) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
  343.  
  344. JsonReader reader = Json.createReader(new StringReader(message));
  345. JsonObject jsonMessage = reader.readObject();
  346.  
  347. broadcast( jsonMessage.getString("message"), jsonMessage.getString("to"), nickname);
  348.  
  349. }
  350.  
  351. @OnError
  352. public void onError(Throwable t) throws Throwable {
  353. log.error("Chat Error: " + t.toString(), t);
  354. }
  355.  
  356.  
  357. private static void broadcast_all(JsonObject msg) {
  358. for (ChatWebsocket client : connections) {
  359. try {
  360. synchronized (client) {
  361. client.session.getBasicRemote().sendText(msg.toString());
  362. }
  363. } catch (IOException e) {
  364. log.debug("Chat Error: Failed to send message to client", e);
  365. connections.remove(client);
  366. try {
  367. client.session.close();
  368. } catch (IOException e1) {
  369. // Ignore
  370. }
  371.  
  372. JsonProvider provider = JsonProvider.provider();
  373. JsonObject removed = provider.createObjectBuilder()
  374. .add("action", "disconnected")
  375. .add("name", client.nickname)
  376. .build();
  377.  
  378. broadcast_all(removed);
  379.  
  380. }
  381. }
  382. }
  383.  
  384.  
  385. private static void broadcast(String msg, String to, String name) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
  386.  
  387. Session jk = hm.get(to);
  388.  
  389. JsonProvider provider = JsonProvider.provider();
  390. JsonObject msg1 = provider.createObjectBuilder()
  391. .add("action", "frndmessage")
  392. .add("message", msg )
  393. .add("to", to)
  394. .add("from", name)
  395. .build();
  396. try {
  397. /* Get database connection */
  398. Connection connection=null;
  399. PreparedStatement ps=null;
  400. String sqlUpdateRecord4=null;
  401. Class.forName("com.mysql.jdbc.Driver").newInstance();
  402. connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/mycvmyportfolio?user=root&password=root");
  403.  
  404. jk.getBasicRemote().sendText(msg1.toString());
  405. sqlUpdateRecord4="Insert into chat(senderemail,receiveremail,message)values(?,?,?)";
  406. ps=connection.prepareStatement(sqlUpdateRecord4);
  407.  
  408. ps.setString(1,name);
  409. ps.setString(2,to);
  410. ps.setString(3,msg);
  411.  
  412. ps.executeUpdate();
  413.  
  414. } catch (IOException e) {
  415. log.debug("Chat Error: Failed to send message to client", e);
  416.  
  417. }
  418.  
  419. }
  420.  
  421. private static void broadcastex(JsonObject conn, String to) {
  422.  
  423. Session jk = hm.get(to);
  424.  
  425. try {
  426. jk.getBasicRemote().sendText(conn.toString());
  427.  
  428. } catch (IOException e) {
  429. log.debug("Chat Error: Failed to send message to client", e);
  430.  
  431. }
  432. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement