The website nettuts provides us one tutorial for HTML 5 web socket based on PHP server,as I am not familiar with PHP , I am trying some other web socket servers instead. I search the web socket server implementation and write demos to test them,but most of them cannot work.Finally I use the faye-websocket ( https://github.com/faye/faye-websocket-node ) as the web socket server to let my first example work.
JavaScript Server Side
First install the module with the following command to get the web socket server code (https://github.com/faye/faye-websocket-node)
npm install faye-websocket
then start the server by the command node server.js(you need to install node.js first)
var WebSocket = require('faye-websocket'),
http = require('http');
var server = http.createServer();
server.addListener('upgrade', function(request, socket, head) {
var ws = new WebSocket(request, socket, head);
ws.onmessage = function(event) {
ws.send(event.data);
};
ws.onclose = function(event) {
console.log('close', event.code, event.reason);
ws = null;
};
});
server.listen(8888);
Now ,come to the client,this time we are using the client code(client.html) from http://net.tutsplus.com.
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function connect(){
var socket;
var host = "ws://localhost:8888";
try{
socket = new WebSocket(host);
message('<p class="event">Socket Status: '+socket.readyState);
socket.onopen = function(){
message('<p class="event">Socket Status: '+socket.readyState+' (open)');
}
socket.onmessage = function(msg){
message('<p class="message">Received: '+msg.data);
}
socket.onclose = function(){
message('<p class="event">Socket Status: '+socket.readyState+' (Closed)');
}
} catch(exception){
message('<p>Error'+exception);
}
function send(){
var text = $('#text').val();
if(text==""){
message('<p class="warning">Please enter a message');
return ;
}
try{
socket.send(text);
message('<p class="event">Sent: '+text)
} catch(exception){
message('<p class="warning">');
}
$('#text').val("");
}
function message(msg){
$('#chatLog').append(msg+'</p>');
}
$('#text').keypress(function(event) {
if (event.keyCode == '13') {
send();
}
});
$('#disconnect').click(function(){
socket.close();
});
}//End connect
$(document).ready(function() {
if(!("WebSocket" in window)){
$('#chatLog, input, button, #examples').fadeOut("fast");
$('<p>Oh no, you need a browser that supports WebSockets. How about <a href="http://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container');
}else{
//The user has WebSockets
connect();
}//End else
});
</script>
Now you can double click the client.html and you have already connected to the web socket server. I am testing this demo using Goolge Chrome 21.0.1180.4 dev-m,Firefox 14.0 and Safari 5.1.7 and they are working properly.
/Files/Bryan/websocketexample.pdf
Python Server Side
There is one python implementation pywebsocket(http://code.google.com/p/pywebsocket/) which we can use to serve as the server. pywebsocket comes with an example in /src/example however these are aimed at the standalone mode,use the command to start the server , the client above can remian the same except the host change ,ws://localhost:8888/echo.
python mod_pywebsocket/standalone.py -p 8888 --allow-draft75 -d example --log-level debug
Java Server Side
Tomcat provides support for WebSocket from the version Tomcat 7.0 and they also give several example applications to demonstrate how to use the websocket, take the echoMessage for example, It provides one way to echo back the message which It receives. copy the EchoMessage servlet to your web project
public class EchoMessage extends WebSocketServlet {
private static final long serialVersionUID = 1L;
private volatile int byteBufSize;
private volatile int charBufSize;
@Override
public void init() throws ServletException {
super.init();
byteBufSize = getInitParameterIntValue("byteBufferMaxSize", 2097152);
charBufSize = getInitParameterIntValue("charBufferMaxSize", 2097152);
}
public int getInitParameterIntValue(String name, int defaultValue) {
String val = this.getInitParameter(name);
int result;
if(null != val) {
try {
result = Integer.parseInt(val);
}catch (Exception x) {
result = defaultValue;
}
} else {
result = defaultValue;
}
return result;
}
@Override
protected StreamInbound createWebSocketInbound(String subProtocol) {
return new EchoMessageInbound(byteBufSize,charBufSize);
}
private static final class EchoMessageInbound extends MessageInbound {
public EchoMessageInbound(int byteBufferMaxSize, int charBufferMaxSize) {
super();
setByteBufferMaxSize(byteBufferMaxSize);
setCharBufferMaxSize(charBufferMaxSize);
}
@Override
protected void onBinaryMessage(ByteBuffer message) throws IOException {
getWsOutbound().writeBinaryMessage(message);
}
@Override
protected void onTextMessage(CharBuffer message) throws IOException {
getWsOutbound().writeTextMessage(message);
}
}
}
configure and add the following to the web.xml
<servlet>
<servlet-name>echo</servlet-name>
<servlet-class>websocket.echo.EchoMessage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>echo</servlet-name>
<url-pattern>/echo</url-pattern>
</servlet-mapping>
Now get connected to the server via the url ws://localhost:8888/[ContextPath]/echo, this demo works properly in Firefox and Chrome, but fails in safari.
Ref
http://java.net/projects/websocket-spec/lists/jsr356-experts/archive/2012-04/message/3
http://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/
https://github.com/faye/faye-websocket-node
http://code.google.com/p/pywebsocket/
http://chemicaloliver.net/internet/getting-started-web-sockets-using-pywebsocket-mod_python-and-apache-in-ubuntu/http://maddemcode.com/web/websockets-and-pywebsocket-quick-dirty-playground/