zoukankan      html  css  js  c++  java
  • java web 在线聊天的基本实现

    随着互联网的发展,http的协议有些时候不能满足需求,比如在现聊天的实现.如果使用http协议必须轮训,或者使用长链接.必须要一个request,这样后台才能发送信息到前端.

    后台不能主动找客户端通信.而且每次请求heard都带有很多的信息.这样也很占用宽带.这是websocket.

    因为主要是为了学习,所以前台很粗糙.没有css.

    1.后台实现

    后台一共有两个类 一个是个imessage类,就是一个信息的bean.另一个类是socket,这个类主要是处理信息的发送.

    Message.java如下:

     1 package com.socket;
     2 
     3 public class Message {
     4     private String id;
     5     private String msg;
     6     private String from;
     7     private String to;
     8 
     9 
    10     public String getFrom() {
    11         return from;
    12     }
    13 
    14     public void setFrom(String from) {
    15         this.from = from;
    16     }
    17 
    18     public String getTo() {
    19         return to;
    20     }
    21 
    22     public void setTo(String to) {
    23         this.to = to;
    24     }
    25 
    26     public String getId() {
    27         return id;
    28     }
    29 
    30     public void setId(String id) {
    31         this.id = id;
    32     }
    33 
    34     public String getMsg() {
    35         return msg;
    36     }
    37 
    38     public void setMsg(String msg) {
    39         this.msg = msg;
    40     }
    41 
    42 }

    socket.Java代码如下:

     1 package com.socket;
     2 
     3 import java.io.IOException;
     4 import java.util.HashMap;
     5 import java.util.Map;
     6 import java.util.Set;
     7 
     8 import javax.websocket.OnMessage;
     9 import javax.websocket.OnOpen;
    10 import javax.websocket.Session;
    11 import javax.websocket.server.ServerEndpoint;
    12 
    13 import com.google.gson.Gson;
    14 
    15 @ServerEndpoint("/websocket")
    16 public class Socket {
    17     public static Map<String, Session> sessionMap = new HashMap<String, Session>();
    18     private Session session;
    19 
    20     @OnOpen
    21     public void startSocket(Session session) {
    22         this.session = session;
    23         System.out.println("链接成功");
    24         if (sessionMap.size() == 0) {
    25             return ;
    26         }
    27         Set userIds = sessionMap.keySet();
    28         StringBuffer sBuffer  = new StringBuffer();
    29         for (Object str : userIds) {
    30             sBuffer.append(str.toString() + ":");
    31         }
    32         Gson gson = new Gson();
    33         try {
    34             Message message = new Message();
    35             message.setFrom("系统");
    36             message.setMsg(sBuffer.toString());
    37             session.getBasicRemote().sendText(gson.toJson(message),true);
    38         } catch (IOException e) {
    39             // TODO Auto-generated catch block
    40             e.printStackTrace();
    41         }
    42     }
    43 
    44     @OnMessage
    45     public void getMessgae(Session session, String str, boolean last) {
    46         if (session.isOpen()) {
    47             try {
    48                 System.out.println(str);
    49                 Gson gson = new Gson();
    50                 Message msg = gson.fromJson(str, Message.class);
    51                 Message toMessage = msg;
    52                 toMessage.setFrom(msg.getId());
    53                 toMessage.setTo(msg.getTo());
    54                 
    55                 if (msg.getMsg().equals("newUser")) {
    56                     if (sessionMap.containsKey(msg.getId())) {
    57                         sessionMap.remove(msg.getId());
    58                     }
    59                     sessionMap.put(msg.getId(), session);
    60                 } else {
    61                     Session toSession = sessionMap.get(msg.getTo());
    62                     if (toSession != null && toSession.isOpen()) {
    63                         toSession.getBasicRemote().sendText(gson.toJson(toMessage).toString(), last);
    64                     } else {
    65                         toMessage.setMsg("用户不存在");
    66                         toMessage.setFrom("系统");
    67                         session.getBasicRemote().sendText(gson.toJson(toMessage).toString(), last);
    68                     }
    69                 }
    70             } catch (IOException e) {
    71                 // TODO Auto-generated catch block
    72                 e.printStackTrace();
    73             }
    74 
    75         } else {
    76             System.out.println("session is closed");
    77         }
    78     }
    79 }

    2 前端代码

    前台主要使用的是Jquery库来操作一些dom. 后台开启的是 8889端口,所以前端要调用 ws://localhost:8889/webChat/websocket,如果自己实现请改自己的端口

    js和html如下:

    <!DOCTYPE html>  
    <html>
        <head>  
            <meta charset="UTF-8">  
            <title>Test WebSocket</title>
            <script type="text/javascript" src="js/jquery.min.js"></script> 
            <script type="text/javascript" >
            $(function() {
                var url = "ws://localhost:8889/webChat/websocket";
                var ws = "";
                var message ={"id":"","msg":"","form":"","to":""};
                function connection() {
                    ws = new WebSocket(url);
                    console.log("connection.......");
                    ws.onmessage = function (e){
                        var json = eval('(' +  e.data.toString() + ')');
                        showMessage(json.from +":"+ json.msg);
                    }
                    ws.onclose = function() {
                        showMessage("close");
                    }
                    ws.onerror = function (e){
                        showMessage("error");
                    }
                    ws.onopen = function() {
                        showMessage("链接成功")
                        message.id = $(".identity").val();
                        message.msg = "newUser";
                        console.log(JSON.stringify(message));
                        ws.send(JSON.stringify(message));
                        message.msg = "";
                        
                    }
                }
               
                
                
                
                $(".start-conn-btn").click(function() {
                    connection();
                });
                $(".send-btn").click(function() {//send message
                    message.to = $(".to-user").val();
                    message.msg = $(".msg-context").val();
                    $(".msg-context").val("");
                    ws.send(JSON.stringify(message));
                    showMessage( "我:" + message.msg );
                    message.msg = "";
                   
                });
                
                function showMessage(msg) {
                    $(".show-message").append( msg + "<br/>");
    
                }
                
                
            });
            
            </script>
        </head>
        <body>
           <div class="container">
               <div calss="item">
               <span>ID:</span>
               <input type="text" class="identity">
               <button class="start-conn-btn" >链接</button>
               <span>toUser:</span>
               <input type="text" class="to-user">
               </div>
               <div class="show-message">
               
               </div>
               <div calss="item">
               <span>内容:</span>
               <textarea  class="msg-context"></textarea>
               </div>
               <div><button class="send-btn">send</button></div>
           </div>
        </body> 
    
    </html>

    以上的这些就是简单的实现一个在线web聊天.

  • 相关阅读:
    Java8 Stream Function
    PLINQ (C#/.Net 4.5.1) vs Stream (JDK/Java 8) Performance
    罗素 尊重 《事实》
    小品 《研发的一天》
    Java8 λ表达式 stream group by max then Option then PlainObject
    这人好像一条狗啊。什么是共识?
    TOGAF TheOpenGroup引领开发厂商中立的开放技术标准和认证
    OpenMP vs. MPI
    BPMN2 online draw tools 在线作图工具
    DecisionCamp 2019, Decision Manager, AI, and the Future
  • 原文地址:https://www.cnblogs.com/guoke-jsp/p/6047496.html
Copyright © 2011-2022 走看看