WebSocket实现简单的web聊天室详解编程语言

1.需要Tomcat7.0所以服务器

2.需要JDK7.0
3.手工加入Tomcat7.0中lib目录下的一下三个包catalina.jar、tomcat-coyote.jar、websocket-api.jar
4.项目部署后,请将服务器中当前项目下的catalina.jar、tomcat-coyote.jar、websocket-api.jar三个包删除。
5.项目目录结构如下


图片

Servlet代码

package com.yc.websockets; 
 
import java.io.IOException; 
import java.nio.ByteBuffer; 
import java.nio.CharBuffer; 
import java.util.ArrayList; 
import java.util.List; 
 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpSession; 
import javax.websocket.OnClose; 
import javax.websocket.OnMessage; 
import javax.websocket.OnOpen; 
import javax.websocket.Session; 
import javax.websocket.server.ServerEndpoint; 
 
import org.apache.catalina.websocket.MessageInbound; 
import org.apache.catalina.websocket.StreamInbound; 
import org.apache.catalina.websocket.WebSocketServlet; 
import org.apache.catalina.websocket.WsOutbound; 
 
@SuppressWarnings({"deprecation","unused", "serial"}) 
public class WebSocketTest extends WebSocketServlet { 
private static List<MyMessageInbound> userList = new ArrayList<MyMessageInbound>(); 
private HttpSession session; 
 
    @Override 
    protected StreamInbound createWebSocketInbound(String str, HttpServletRequest request) { 
     session=request.getSession(); 
        return new MyMessageInbound(); 
    } 
 
    private class MyMessageInbound extends MessageInbound { 
        WsOutbound myoutbound; 
 
        /** 
         * 当用户登录时,WebSocket握手完成,创建完毕,WsOutbound用于向客户端发送数据 
         */ 
public void onOpen(WsOutbound outbound) { 
            try { 
                System.out.println("Open Client."); 
                this.myoutbound = outbound; 
                userList.add(this); //添加当前用户 
                 
                //向客服端发送信息 
                outbound.writeTextMessage(CharBuffer.wrap("Hello!")); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 
 
/** 
 * 用户退出时,WebSocket关闭事件,参数status应该来自org.apache.catalina.websocket.Constants 
 * 中定义的几个常量,可以参考文档或者核对一下Tomcat的源码 
 */ 
        @Override 
        public void onClose(int status) { 
            userList.remove(this); //移除当前用户 
        } 
 
       /** 
        * 接受用户发过来的信息,有文本消息数据到达 
        */ 
        @Override 
        public void onTextMessage(CharBuffer cb) throws IOException { 
            for (MyMessageInbound mmib:userList){ //循环向所有在线用户发送当前用户的信息 
                CharBuffer buffer = CharBuffer.wrap(cb); 
                mmib.myoutbound.writeTextMessage(buffer); //调用指定用户的发送方法发送当前用户信息 
                mmib.myoutbound.flush(); //清空缓存 
            } 
        } 
 
        /** 
         * 有二进制消息数据到达,暂时没研究出这个函数什么情况下触发,js的WebSocket按理说应该只能send文本信息才对 
         */ 
        @Override 
        public void onBinaryMessage(ByteBuffer bb) throws IOException { 
        } 
    } 
}

web.xml配置文件 

<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee ; 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 
<display-name></display-name> 
   
<servlet> 
<servlet-name>webServlet</servlet-name> 
<servlet-class>com.yc.websockets.WebSocketTest</servlet-class> 
</servlet> 
<servlet-mapping> 
<servlet-name>webServlet</servlet-name> 
<url-pattern>/webServlet</url-pattern> 
</servlet-mapping> 
<welcome-file-list> 
<welcome-file>index.html</welcome-file> 
</welcome-file-list> 
</web-app>


index.html

<!DOCTYPE html> 
<html> 
<head> 
<meta charset=UTF-8> 
<title>Tomcat WebSocket Chat</title> 
<script> 
//设定WebSocket,注意协议是ws,请求是指向对应的WebSocketServlet的 
/*设定WebSocket,注意协议是ws,请求是指向对应的WebSocketServlet的 
var url = "ws://127.0.0.1:8080/j2ee6/echo.ws"; 
// 创建WebSocket实例,下面那个MozWebSocket是Firefox的实现 
if ('WebSocket' in window) { 
ws = new WebSocket(url); 
} else if ('MozWebSocket' in window) { 
ws = new MozWebSocket(url); 
} else { 
alert('Unsupported.'); 
return; 
}*/ 
var ws = new WebSocket("ws://218.196.14.208:8080/webSocket/webServlet"); 
 
//WebSocket握手完成,连接成功的回调 
//有个疑问,按理说new WebSocket的时候就会开始连接了,如果在设置onopen以前连接成功,是否还会触发这个回调 
ws.onopen = function() { 
//请求成功 
}; 
 
//收到服务器发送的文本消息, event.data表示文本内容 
ws.onmessage = function(message) { 
document.getElementById("talkInfo").innerHTML+=message.data+"<hr style='border: 1px dashed #CCC'/>"; 
}; 
 
//关闭WebSocket的回调 
ws.onclose = function() { 
//alert('Closed!'); 
}; 
 
// 通过WebSocket想向服务器发送一个文本信息 
function postToServer() { 
ws.send(document.getElementById("content").value); 
document.getElementById("content").value = ""; 
} 
 
//关闭WebSocket 
function closeConnect() { 
ws.close(); 
} 
</script> 
<style> 
* { 
margin: 0 auto; 
padding: 0px; 
font-size: 12px; 
font-family: "微软雅黑"; 
line-height: 26px; 
} 
 
#bigbox { 
margin:0px auto; 
padding:0px; 
width:70%; 
} 
 
#talkInfo{ 
width:100%; 
height:500px; 
border:1px solid red; 
overflow: scorll; 
} 
 
#operation{ 
width:100%; 
height:30px; 
margin-top:10px; 
} 
 
#content{ 
height:30px; 
line-height:30px; 
} 
</style> 
</head> 
<body> 
<div id="bigbox"> 
<div id="talkInfo"></div> 
<div id="operation"> 
<center> 
<input type="text" name="content" id="content" size="100"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
<input type="button" value=" &nbsp;发送&nbsp; " onclick="postToServer()" />&nbsp;&nbsp; 
<input type="button" value=" &nbsp;我闪 &nbsp; " onclick="closeConnect()" /> 
</center> 
</div> 
</div> 
</body> 
</html> 

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/11106.html

(0)
上一篇 2021年7月19日 10:41
下一篇 2021年7月19日 10:41

相关推荐

发表回复

登录后才能评论