Los requisitos ambientales por lo menos jdk1.7, tomcat7
pom.xml
<dependency> <groupId> javax </ groupId> <artifactId> JavaEE-api </ artifactId> <versión> 7.0 </ version> <scope> proporcionado </ scope> </ dependency>
WebSocket.java
com.websockets paquete; Importación javax.websocket * ;. importación javax.websocket.server.ServerEndpoint; Importación java.io.IOException; Importación java.util.concurrent.CopyOnWriteArrayList; @ServerEndpoint (value = "/ WebSocket") public class un WebSocket { / ** * con la sesión de conexión con un cliente, tiene que ser enviada al cliente por los datos * / privada de la sesión de la sesión; un privado CopyOnWriteArrayList estática <a WebSocket> sockets un CopyOnWriteArrayList nuevos nuevos = <> (); / ** * Crear * @ la sesión de parámetro * / @OnOpen public void del onOpen (la sesión de la sesión) { this.session = la sesión; System.out.println ( "Crear"); sockets.add (el presente); } / ** *发送消息 * @param mensaje * @throws IOException * / @OnMessage public void sendMessage (String mensaje) throws IOException { for (WebSocket WebSocket: enchufes) { . WebSocket.session.getBasicRemote () SendText (mensaje); } } / ** *关闭 * / @OnClose pública onClose void () { sockets.remove (this); } / ** *发生错误 * @param sesión * @param de error * / @OnError pública onError vacío (Session session, el error Throwable) { System.out.println ( "发生错误"); error.printStackTrace (); } }
página de llamada de chat
pagina.html
<HTML! DOCTYPE> <HTML> <head> <meta charset = "UTF-8."> <Title> Interfaz de conversación </ title> <style> / ** restablecimiento de valores predeterminados etiqueta de estilos * / * { margin: 0; padding : 0; list-style: none; font-family: 'Microsoft Yahei' } #container { ancho: 450px; altura: 780px; fondo: #eee; margen: 80px auto 0; position: relative; box-shadow: 20px # 777 55 px 20px; } .header { background: # 000; altura: 40 píxeles; Color: #fff; derecha: 80px; line-height: 34px; font-size: 20px; padding: 0 10px; } .Footer { anchura: 430px; altura: 50px; background: # 666; position: absolute; parte inferior: 0; padding: 10px; } De entrada .footer { anchura: 275px; altura: 45px; Esquema: ninguna; font-size: 20px; text-indent: 10px; position: absolute; frontera de radio: 6px; } Lapso .footer { display: inline-block; anchura: 62px; altura: 48px; Antecedentes: #ccc; font-weight: 900; line-height: 45px; Cursor: puntero; text-align: center; position: absolute; derecha: 10px; frontera de radio: 6px; } .Footer útil: hover { color de: #fff; background: # 999; } #User_face_icon { display: inline-block; fondo: rojo; anchura: 60 píxeles; altura: 60 píxeles; border-radius: 30px; position: absolute; parte inferior: 6px; la izquierda: 14px; Cursor: puntero; overflow: hidden; } Img { anchura: 60 píxeles; altura: 60 píxeles; } .Este contenido { font-size: 20px; anchura: 435px; altura: 662px; overflow: auto; padding: 5px; } .Este contenido ha sido li { margin-top: 10px; padding-left: 10px; anchura: 412px; bloqueo de pantalla; Limpia los dos; overflow: hidden; } .Este contenido ha sido li img { float: left; } Lapso li .Este contenido { background: # 7cfc00; padding: 10px; border-radius: 10px; flotador izquierdo; margen: 6px 10px 0 10px; max-width: 310px; frontera: #ccc sólido 1px; box-shadow: 0 0 3px #ccc; } .Este contenido ha sido li img.imgleft { float: left; } Img.imgright li .Este contenido { float: right; } Li {.Este contenido span.spanleft Float: left; Antecedentes: #fff; } Span.spanright li .Este contenido { float: right; background: # 7cfc00; } </ Style> </ head> <body> <div id = "contenedor"> <div class = "header"> <span style = "float: left;">业余草:模拟微信聊天界面</ span> <span style = "float: right;"> 14:21 </ span> </ div> <ul class = "contenido"> </ ul> <div class = "pie"> <div id = "user_face_icon"> <img src = "http://www.xttblog.com/icons/favicon.ico" alt = ""> <Script> la window.onload = function () { var WebSocket = null; SI (WebSocket == null) { / * WS: // localhost: 8080 / * WebSocket dirección de prueba / llamada WebSocket / WebSocket un WebSocket nuevos nuevos = ( 'WS : // localhost: 8080 / Prueba / WebSocket '); } else { alert ( "navegador no soporta WebSocket"); } / * error * / webSocket.onerror = function (event) { el console.log (Evento); }; / * Crear * / webSocket.onopen = function (event) { el onMessage ( "chat de grupo"); }; el onMessage (el event.data); / * Escuchar los mensajes * / = Función webSocket.onmessage (Event) { };
/ * Cerrar * /
webSocket.onclose = function (event) {
}; var arrIcon = [ 'HTTPS: //c-ssl.duita_EyjSF.thumb.700_0.jpeg', ' HTTPS: //c-ssl.duitan0_0.jpeg ']; var NUM = 0; // cambiar la imagen de control var iNow = -1; // cambiado para acumular alrededor de la flotante var icon = document.getElementById (' user_face_icon ' ). la getElementsByTagName ( 'IMG'); var BTN = document.getElementById ( 'BTN'); texto var = document.getElementById ( 'texto'); contenido var document.getElementsByTagName = ( 'UL') [0]; var IMG contenido = .getElementsByTagName ( 'IMG'); lapso var = contenido.getElementsByTagName ( 'lapso'); + Valor + '</ span> </ li>'; SI (text.value == '') { alert ( 'No enviar mensaje vacío'); } else {
/ * Enviar mensaje * / webSocket.send (text.value); iNow ++; IMG [iNow] + = .className ' imgright '; lapso [iNow] + = .className' spanright '; text.value =' '; // contenido es demasiado grande, la barra de desplazamiento se coloca en el fondo del contentcontent.scrollTop = content.scrollHeight; } } funcionar el onMessage (valor ) { content.innerHTML + = '<Li> <IMG sRC = "' + arrIcon [0] + '"> <span>' + valor + '</ span> </ Li>'; } </ Script> } </ Html>