HTML5 WebSocket 传输消息、图片、音频

本文基于Tomcat7.0.37的chat示例,详细讲解如何使用HTML5的WebSocket技术进行文本、图片和音频的实时传输。核心代码展示了WebSocket在多媒体交互中的应用。
部署运行你感兴趣的模型镜像

根据Tomcat7.0.37 chat 官方例子修改,核心代码如下:

/*
 * 
 */
package com.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;

/**
 * Example web socket servlet for chat.
 */
@SuppressWarnings("serial")
public class ChatWebSocketServlet extends WebSocketServlet 
{
	//private static final String GUEST_PREFIX="Guest";
	//private final AtomicInteger connectionIds=new AtomicInteger(0);
    //private final Set<ChatMessageInbound> connections=new CopyOnWriteArraySet<ChatMessageInbound>();
    protected StreamInbound createWebSocketInbound(String subProtocol,HttpServletRequest request) 
    {
    	System.out.println(subProtocol+"...");
    	System.out.println(request.getParameter("cs"));
    	HttpSession session=request.getSession();
    	String sessionId=session.getId();
    	ChatMessageInbound chatMessageInbound=new ChatMessageInbound();
    	chatMessageInbound.setSessionId(sessionId);
    	return chatMessageInbound;
    }
    /*
    public class ChatMessageInbound extends MessageInbound 
    {
    	private String nickname;
    	public ChatMessageInbound()
    	{
    		
    	}
    	public ChatMessageInbound(int id) 
    	{
    		this.nickname=GUEST_PREFIX+id;
        }
    	protected void onOpen(WsOutbound outbound) 
    	{
    		connections.add(this);
            String message=String.format("* %s %s",nickname,"has joined.");
            broadcast(message);
        }
    	protected void onClose(int status)
    	{
    		connections.remove(this);
            String message=String.format("* %s %s",nickname,"has disconnected.");
            broadcast(message);
        }
    	protected void onBinaryMessage(ByteBuffer message) throws IOException 
    	{
    		throw new UnsupportedOperationException("Binary message not supported.");
        }
    	protected void onTextMessage(CharBuffer message) throws IOException 
    	{
            // Never trust the client
            String filteredMessage=String.format("%s: %s",nickname,
            		HTMLFilter.filter(message.toString()));
            broadcast(filteredMessage);
        }
    	public void broadcast(String message) 
    	{
            for(ChatMessageInbound connection : connections)
            {
                try 
                {
                    CharBuffer buffer=CharBuffer.wrap(message);
                    connection.getWsOutbound().writeTextMessage(buffer);
                } 
                catch(IOException ignore) 
                {
                    // Ignore
                }
            }
        }
    }
    */
}


package com.servlet;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;

public class ChatMessageInbound extends MessageInbound
{
	private String sessionId;
	public String getSessionId() 
	{
		return sessionId;
	}
	public void setSessionId(String sessionId) 
	{
		this.sessionId=sessionId;
	}
	protected void onOpen(WsOutbound outbound) 
	{
		InitServlet.socketList.add(this);
    }
	protected void onClose(int status)
	{
		InitServlet.socketList.remove(this);
    }
	protected void onBinaryMessage(ByteBuffer message) throws IOException 
	{
		
    }
	protected void onTextMessage(CharBuffer message) throws IOException 
	{
		//String filteredMessage=String.format("%s: %s",sessionId,
        //		HTMLFilter.filter(message.toString()));
        //broadcast(filteredMessage);
		InitServlet.broadcast(message.toString());
    }
	/*
	public void broadcast(String message)
	{
		System.out.println(InitServlet.socketList.size()+".....");
        for(ChatMessageInbound connection : InitServlet.socketList)
        {
            try 
            {
                CharBuffer buffer=CharBuffer.wrap(message);
                connection.getWsOutbound().writeTextMessage(buffer);
            }
            catch(Exception e) 
            {
            	System.out.println(e.getMessage());
            }
        }
    }
    */
}

package com.servlet;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.util.HTMLFilter;

@SuppressWarnings("serial")
public class InitServlet extends HttpServlet
{
	public static Set<ChatMessageInbound> socketList;
	public void init(ServletConfig config) throws ServletException 
	{
		socketList=new CopyOnWriteArraySet<ChatMessageInbound>();
		super.init(config);
	}
	public void destroy() 
	{
		super.destroy();
		socketList.clear();
		socketList=null;
	}
	public static Set<ChatMessageInbound> getSocketList()
	{
		return socketList;
	}
	public static void broadcast(String message)
	{
		System.out.println(InitServlet.socketList.size()+".....");
        for(ChatMessageInbound connection : InitServlet.socketList)
        {
            try 
            {
            	String tmpmessage=String.format("%s: %s",connection.getSessionId(),
                		HTMLFilter.filter(message.toString()));
                CharBuffer buffer=CharBuffer.wrap(tmpmessage);
                connection.getWsOutbound().writeTextMessage(buffer);
            }
            catch(Exception e) 
            {
            	System.out.println(e.getMessage());
            }
        }
    }
	public static void broadcast(byte b[])
	{
		System.out.println(InitServlet.socketList.size()+".....");
		for(ChatMessageInbound connection : InitServlet.socketList)
		{
            try 
            {
                ByteBuffer buffer=ByteBuffer.wrap(b);
                connection.getWsOutbound().writeBinaryMessage(buffer);
            }
            catch(Exception e) 
            {
            	System.out.println(e.getMessage());
            }
        }
	}
}

<!DOCTYPE html>
<html>
  <head>
    <title>chat.html</title>
    <meta charset="UTF-8">
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=UTF-8">
    <style type="text/css">
    	input#chat 
    	{
    		width:410px
        }
        #console-container 
        {
        	width:400px;
        }
        #console 
        {
        	border:1px solid #CCCCCC;
            border-right-color:#999999;
            border-bottom-color:#999999;
            height:170px;
            overflow-y:scroll;
            padding:5px;
            width:100%;
        }
        #console p 
        {
            padding:0;
            margin:0;
        }
    </style>
    <script type="text/javascript">
		var audioContext=new (window.AudioContext || window.webkitAudioContext)();
    	var Chat={};
    	Chat.socket=null;
    	Chat.connect=(function(host)
    	{
    		if("WebSocket" in window) 
    		{
    			Chat.socket=new WebSocket(host);
            } 
            else if("MozWebSocket" in window) 
            {
                Chat.socket=new MozWebSocket(host);
            } 
            else 
            {
                Console.log("Error: WebSocket is not supported by this browser.");
                return;
            }
            Chat.socket.onopen=function() 
            {
                Console.log("Info: WebSocket connection opened.");
                document.getElementById("chat").onkeydown=function(event) 
                {
                    if(event.keyCode==13) 
                    {
                        Chat.sendMessage();
                    }
                };
            };
            Chat.socket.onclose=function() 
            {
            	document.getElementById("chat").onkeydown=null;
                Console.log("Info: WebSocket closed.");
            };
            Chat.socket.onmessage=function(message) 
            {
                //Console.log(message.data);
                /*
                if(typeof(message.data)=="string")
                {
                	Console.log(message.data);
                }
                else 
                {
                	var reader=new FileReader();
                	var imgDiv=document.getElementById("imgDiv");
                	imgDiv.innerHTML="";
                	reader.onload=function(event) 
                	{
                		if(event.target.readyState==FileReader.DONE)
                		{
                			//var picdata=event.target.result;
							//img.innerHTML="<img src='"+picdata+"'/>";
							var image=new Image();
							image.src=event.target.result; // 显示图片的地方
							imgDiv.appendChild(image);
						}
					};
					reader.readAsDataURL(message.data);
				}
				*/
				var reader=new FileReader();
				reader.onload=function(evt)
            	{
            		if(evt.target.readyState==FileReader.DONE)
                	{
                		audioContext.decodeAudioData(evt.target.result,function(buffer) 
                		{
                			//解码成pcm流
                            var audioBufferSouceNode=audioContext.createBufferSource();
                            audioBufferSouceNode.buffer=buffer;
                            audioBufferSouceNode.connect(audioContext.destination);
                            audioBufferSouceNode.start(0);
                        },
                        function(e)
                        {
                        	console.log(e);
                        });
                        /*
                        var source=audioContext.createBufferSource(); // creates a sound source
  						source.buffer=evt.target.result;                    // tell the source which sound to play
  						source.connect(audioContext.destination);       // connect the source to the context's destination (the speakers)
  						source.start(0);
  						*/
                	}
            	};
            	reader.readAsArrayBuffer(message.data);
            };
        });
        Chat.initialize=function() 
        {
        	if(window.location.protocol=="http:") 
        	{
                Chat.connect("ws://"+window.location.host+"/lwzz/websocket/chat?cs=cwt");
            }
            else
            {
                Chat.connect("wss://"+window.location.host+"/lwzz/websocket/chat");
            }
        };
        Chat.sendMessage=(function() 
        {
            var message=document.getElementById("chat").value;
            if(message!="") 
            {
                Chat.socket.send(message);
                document.getElementById("chat").value="";
            }
        });
        var Console={};
        Console.log=(function(message) 
        {
        	var console=document.getElementById("console");
            var p=document.createElement("p");
            p.style.wordWrap="break-word";
            p.innerHTML=message;
            console.appendChild(p);
            while(console.childNodes.length>25) 
            {
            	console.removeChild(console.firstChild);
            }
            console.scrollTop=console.scrollHeight;
        });
        Chat.initialize();
    </script>
  </head>
  <body>
    <noscript>
    	<h2 style="color: #ff0000">
    		Seems your browser doesn't support Javascript! 
    		Websockets rely on Javascript being enabled. Please enable
    		Javascript and reload this page!
    	</h2>
    </noscript>
    <div>
    	<p>
    		<input type="text" placeholder="type and press enter to chat" id="chat">
    	</p>
    	<div id="console-container">
        	<div id="console"></div>
    	</div>
	</div>
	<div id="imgDiv" style="border-left-width:0px;margin-left:450px;margin-top:0px;padding-top:30px;">
	</div>
  </body>
</html>



您可能感兴趣的与本文相关的镜像

Anything-LLM

Anything-LLM

AI应用

AnythingLLM是一个全栈应用程序,可以使用商用或开源的LLM/嵌入器/语义向量数据库模型,帮助用户在本地或云端搭建个性化的聊天机器人系统,且无需复杂设置

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值