隨着互聯網的發展,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聊天.