Thursday, 28 November 2013

Web Socket

WebSocket is a protocol providing full-duplex communications channels over a single TCP connection.It enables two-way communication between  clients running untrusted code in a controlled environment to a remote host that has opted-in to communications from that code.The security model used for this is the origin-based security model commonly used by web browsers.The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C.

This is independent TCP-based protocol and consist of an opening handshake followed by basic message framing.this technology is to provide a mechanism for browser-based application that need two-way communication with server that does not depend on opening multiple Http connections.

Opening Handshake:
                   To stablish a connection, the client sends a websocket handshake request as like following:

 Get /path     //path where client will connect
 Host:myexample.com  // host name
 Upgrade : websocket
 Connection:Upgrade
 Sec-WebSocket-Key: xyschsdbvhh12== // a random value that has been base64 encoded for the handshake request
 Origin: http://example.com // origin ofr the request
 Sec-WebSocket-Version: ** //

Server sends the response like this:
 HTTP/1.1 101
 Upgrade: websocket
 Connection: Upgrade
 Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=

In the response server append a magic string to Sec-Websocket-key and then hashed the resulting sting with SHA-1 then base64 encoded.this resulting key is send to client as Sec-WebSocket-Accept.

// we can open handshake by empty websocket request.


Ruby Implementation of WebSocket

 //WebSocket Server
================================================
  require 'web_socket'
  server = WebSocketServer.new(:port => 4000, :accepted_domains => ["*"])
  puts("Server is running at port %d" % server.port)
  server.run() do |ws|
  puts("Connection accepted")
  puts("Path: #{ws.path}, Origin: #{ws.origin}")

  if ws.path == "/"
    puts"========== client connected============="
    ws.handshake()
  end
    puts("Connection closed")
  end



// WebSocket Implementation

require 'web_socket'
client = WebSocket.new('ws://hostname:4000/')
puts("Connected")
Thread.new() do
  while data = client.receive()
    printf("Received: %p\n", data)
  end
  exit()
end
$stdin.each_line() do |line|
  data = line.chomp()
  client.send(data)
end
client.close()




















No comments:

Post a Comment