Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <title> Chat</title>
- <link rel="stylesheet" type="text/css" href="Bootstrap/chat.css" />
- <script src="Bootstrap/jquery.js"></script>
- <style type="text/css">
- input#chat {
- width: 410px
- }
- #console-container {
- width: 400px;
- }
- #console {
- border: 1px solid #CCCCCC;
- border-right-color: #999999;
- border-bottom-color: #999999;
- height: 170px;
- overflow-y: scroll;
- padding: 5px;
- width: 100%;
- }
- #console p {
- padding: 0;
- margin: 0;
- }
- </style>
- var host = window.location.host;
- var path = window.location.pathname;
- var webCtx = path.substring(0, path.indexOf('/', 1));
- var endPointURL = "ws://" + window.location.host + webCtx + "/user /chatonline";
- var Chat = {};
- var windows_ass = {};
- var message_holder = {};
- Chat.socket = null;
- Chat.connect = (function(host) {
- if ('WebSocket' in window) {
- Chat.socket = new WebSocket(host);
- } else if ('MozWebSocket' in window) {
- Chat.socket = new MozWebSocket(host);
- } else {
- alert("Some thing went wrong!!");
- return;
- }
- Chat.socket.onopen = function () {
- // var to = $(this).attr('data-to');
- // alert(to);
- $('.message' ).keydown(function(event) {
- if (event.keyCode == 13) {
- var mto = $(this).attr('data-to');
- // alert(mto);
- var text = $(this).val();
- sendMessage(mto,text);
- $(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/>");
- $(this).val('');
- }
- });
- };
- Chat.socket.onclose = function () {
- document.getElementById('chat').onkeydown = null;
- };
- Chat.socket.onmessage = function (event) {
- var div = document.getElementById('online');
- var message = JSON.parse(event.data);
- if(message.action == 'connected'){
- 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>";
- }
- if(message.action == 'disconnected')
- {
- var to_remove = document.getElementById(message.name);
- to_remove.remove();
- }
- if(message.action == 'frndmessage'){
- if(windows_ass[message.from] !== undefined )
- {
- $('.'+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/>");
- }else{
- if(message_holder[message.from] === undefined)
- {
- message_holder[message.from] = [];
- }
- var fr = message.from;
- message_holder[fr].push(message.message);
- $('#'+message.from+ ' i').html(message_holder[fr].length);
- }
- }
- };
- });
- Chat.initialize = function() {
- //var name = getParameterByName('name');
- if (window.location.protocol == 'http:') {
- Chat.connect(endPointURL);
- } else {
- Chat.connect(endPointURL);
- }
- };
- function sendMessage(mto,message){
- var information = {
- action: "Message",
- to: mto,
- message: message
- };
- if (message != '') {
- Chat.socket.send(JSON.stringify(information));
- }
- }
- Chat.initialize();
- document.addEventListener("DOMContentLoaded", function() {
- // Remove elements with "noscript" class - <noscript> is not allowed in XHTML
- var noscripts = document.getElementsByClassName("noscript");
- for (var i = 0; i < noscripts.length; i++) {
- noscripts[i].parentNode.removeChild(noscripts[i]);
- }
- }, false);
- </script>
- <h2>Chat Using WebSockets: Tomcat server</h2>
- <div id="online">
- </div>
- <div class="window1">
- <div class="header">
- <div style="float:left;margin-left: 9px;color: white;margin-top: 3px" class="from"></div>
- <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"
- x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24" xml:space="preserve"></svg>
- </div>
- <div class="content"> </div>
- <input type="text" class="message" style="width: 272px;height: 30px;" data-to="" />
- </div>
- <div class="window2">
- <div class="header">
- <div style="float:left;margin-left: 9px;color: white;margin-top: 3px" class="from"></div>
- <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"
- x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24" xml:space="preserve"></svg>
- </div>
- <div class="content"> </div>
- <input type="text" class="message" style="width: 272px;height: 30px;" data-to="" />
- </div>
- <div class="window3">
- <div class="header">
- <div style="float:left;margin-left: 9px;color: white;margin-top: 3px" class="from"></div>
- <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"
- x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24" xml:space="preserve">
- </div>
- <div class="content"> </div>
- <input type="text" class="message" style="width: 272px;height: 30px;" data-to="" />
- </div>
- <script>
- var windows = [] ;
- $( "body" ).on( 'click', '#online li', function (){
- var mesg_to = $(this).attr('id');
- if( windows.indexOf("window1") === -1){
- windows_ass[mesg_to] = "window1";
- windows.push("window1");
- $(".window1").show();
- $(".window1 .from").text(mesg_to);
- $('.window1 input').attr( 'data-to', mesg_to);
- if(message_holder[mesg_to] !== undefined)
- {
- var lengt = message_holder[mesg_to].length;
- for (var i = 0; i<lengt; i++) {
- $('.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/>");
- }
- }
- }
- else if( windows.indexOf("window2") === -1 )
- {
- windows_ass[mesg_to] = "window2";
- windows.push("window2");
- $(".window2").show();
- $(".window2 .from").text(mesg_to);
- $('.window2 input').attr( 'data-to', mesg_to);
- }
- else {
- windows_ass[mesg_to] = "window3";
- windows.push("window3");
- $(".window3").show();
- $(".window3 .from").text(mesg_to);
- $('.window3 input').attr( 'data-to', mesg_to);
- }
- });
- </script>
- @Override
- public void modifyHandshake(ServerEndpointConfig sec,
- HandshakeRequest request,
- HandshakeResponse response)
- {
- sec.getUserProperties().put("email",(String)((HttpSession)request.getHttpSession()).getAttribute("email"));
- }
- private static final Log log = LogFactory.getLog(ChatWebsocket.class);
- static Map<String, Session> hm = new HashMap<String, Session>( );
- private static final Set<ChatWebsocket> connections = new CopyOnWriteArraySet<ChatWebsocket>();
- private String nickname;
- private Session session;
- private String to;
- JsonProvider provider = JsonProvider.provider();
- public ChatWebsocket() {
- }
- @OnOpen
- public void start(EndpointConfig config, Session session) {
- this.session = session;
- connections.add(this);
- nickname= (String) session.getUserProperties().put("email",config.getUserProperties().get("email"));
- //nickname = name;
- // if(nickname.equals(config.getUserProperties().get("email")))
- hm.put(nickname, session);
- JsonObject connected = provider.createObjectBuilder()
- .add("action", "connected")
- .add("name", nickname)
- .build();
- broadcast_all(connected);
- JSONObject obj = new JSONObject();
- obj.put("to",to);
- System.out.println(to);
- //let send about existing users.
- /*JsonReader reader=new JsonReader();
- JsonObject jsonMessage = reader.readObject();
- System.out.println("to:"+jsonMessage.getString("to"));*/
- for (Map.Entry<String, Session> entry : hm.entrySet()) {
- if(entry.getKey().equals(nickname)){
- //System.out.println("double:"+entry.getKey());
- } else {
- JsonObject conn = provider.createObjectBuilder()
- .add("action", "connected")
- .add("name",entry.getKey() )
- .build();
- broadcastex(conn, nickname);
- }
- }
- }
- @OnClose
- public void end() {
- connections.remove(this);
- JsonObject dis = provider.createObjectBuilder()
- .add("action", "disconnected")
- .add("name", nickname)
- .build();
- broadcast_all(dis);
- }
- @OnMessage
- public void incoming(String message) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
- JsonReader reader = Json.createReader(new StringReader(message));
- JsonObject jsonMessage = reader.readObject();
- broadcast( jsonMessage.getString("message"), jsonMessage.getString("to"), nickname);
- }
- @OnError
- public void onError(Throwable t) throws Throwable {
- log.error("Chat Error: " + t.toString(), t);
- }
- private static void broadcast_all(JsonObject msg) {
- for (ChatWebsocket client : connections) {
- try {
- synchronized (client) {
- client.session.getBasicRemote().sendText(msg.toString());
- }
- } catch (IOException e) {
- log.debug("Chat Error: Failed to send message to client", e);
- connections.remove(client);
- try {
- client.session.close();
- } catch (IOException e1) {
- // Ignore
- }
- JsonProvider provider = JsonProvider.provider();
- JsonObject removed = provider.createObjectBuilder()
- .add("action", "disconnected")
- .add("name", client.nickname)
- .build();
- broadcast_all(removed);
- }
- }
- }
- private static void broadcast(String msg, String to, String name) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
- Session jk = hm.get(to);
- JsonProvider provider = JsonProvider.provider();
- JsonObject msg1 = provider.createObjectBuilder()
- .add("action", "frndmessage")
- .add("message", msg )
- .add("to", to)
- .add("from", name)
- .build();
- try {
- /* Get database connection */
- Connection connection=null;
- PreparedStatement ps=null;
- String sqlUpdateRecord4=null;
- Class.forName("com.mysql.jdbc.Driver").newInstance();
- connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/mycvmyportfolio?user=root&password=root");
- jk.getBasicRemote().sendText(msg1.toString());
- sqlUpdateRecord4="Insert into chat(senderemail,receiveremail,message)values(?,?,?)";
- ps=connection.prepareStatement(sqlUpdateRecord4);
- ps.setString(1,name);
- ps.setString(2,to);
- ps.setString(3,msg);
- ps.executeUpdate();
- } catch (IOException e) {
- log.debug("Chat Error: Failed to send message to client", e);
- }
- }
- private static void broadcastex(JsonObject conn, String to) {
- Session jk = hm.get(to);
- try {
- jk.getBasicRemote().sendText(conn.toString());
- } catch (IOException e) {
- log.debug("Chat Error: Failed to send message to client", e);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement