根据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>
本文基于Tomcat7.0.37的chat示例,详细讲解如何使用HTML5的WebSocket技术进行文本、图片和音频的实时传输。核心代码展示了WebSocket在多媒体交互中的应用。
746

被折叠的 条评论
为什么被折叠?



