html5 websocket 简单实现

来源:互联网 发布:python运维脚本实例 编辑:程序博客网 时间:2024/06/12 01:20
前提条件:

导入: javaee-api-7.0.jar


第一步

服务端代码实现: 建立WebSocketServer

@ServerEndpoint(value="/chat")public class WebSocketServer{@OnMessage  public void onMessage(String message, Session session)    throws IOException, InterruptedException {       System.out.println("Received: " + message);       session.getBasicRemote().sendText("This is the first server message");       int sentMessages = 0;    while(sentMessages < 3){      Thread.sleep(5000);      session.getBasicRemote().        sendText("This is an intermediate server message. Count: "          + sentMessages);      sentMessages++;    }       // Send a final message to the client    session.getBasicRemote().sendText("This is the last server message");  }     @OnOpen  public void onOpen() {    System.out.println("Client connected");  }   @OnClose  public void onClose() {    System.out.println("Connection closed");  }}











第二步

html页面实现: 在webapp 下面建立 MySocket.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript" src="jquery-1.8.3.min.js"></script><script type="text/javascript">  var socketManager = {  socket : [],  url : 'ws://localhost:8090/WebTest/chat',  connec : function(){  window.WebSocket = window.WebSocket || window.MozWebSocket;  if(!window.WebSocket){ alert("浏览器不支持webSocket"); return;  }  this.socket = new WebSocket(this.url);  this.socket.onopen = function(){alert("server connect");};  this.socket.onclose = function(){alert("server is closed");};  this.socket.onmessage = function(msg){  alert(msg.data);  };  },  sendMsg : function(msg){  if (this.socket) {                  this.socket.send(msg);                  return true;              }              alert('please connect to the server first !!!');              return false;    }  };  socketManager.connec();   $(function(){  $("#button_send").click(function(){  socketManager.sendMsg($("#text_msg").val());  });  });  </script></head><body>  发送信息:  <input type="text" id="text_msg"/>   <input type="button" value="发送" id="button_send" /></body></html>




三   将项目部署到tomcat,输入地址:http://localhost:8090/WebTest/MySocket.jsp(注意:由于tomcat实现了websocket,所以不熟的时候不能将JAVAee-API-7.0.jar发布到tomcat下面)


0 0
原创粉丝点击