Search Results

Search found 1063 results on 43 pages for 'em websocket'.

Page 1/43 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • WebSocket handshake with Ruby and EM::WebSocket::Server

    - by Chad Johnson
    I am trying to create a simple WebSocket connection in JavaScript against my Rails app. I get the following: WebSocket connection to 'ws://localhost:4000/' failed: Error during WebSocket handshake: 'Sec-WebSocket-Accept' header is missing What am I doing wrong? Here is my code: JavaScript: var socket = new WebSocket('ws://localhost:4000'); socket.onopen = function() { var handshake = "GET / HTTP/1.1\n" + "Host: localhost\n" + "Upgrade: websocket\n" + "Connection: Upgrade\n" + "Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\n" + "Sec-WebSocket-Protocol: quote\n" + "Sec-WebSocket-Version: 13\n" + "Origin: http://localhost\n"; socket.send(handshake); }; socket.onmessage = function(data) { console.log(data); }; Ruby: require 'rubygems' require 'em-websocket-server' module QuoteService class WebSocket < EventMachine::WebSocket::Server def on_connect handshake_response = "HTTP/1.1 101 Switching Protocols\n" handshake_response << "Upgrade: websocket\n" handshake_response << "Connection: Upgrade\n" handshake_response << "Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=\n" handshake_response << "Sec-WebSocket-Protocol: quote\n" send_message(handshake_response) end def on_receive(data) puts 'RECEIVED: ' + data end end end EventMachine.run do print 'Starting WebSocket server...' EventMachine.start_server '0.0.0.0', 4000, QuoteService::WebSocket puts 'running' end The handshake headers are per Wikipedia.

    Read the article

  • WebSocket Samples in GlassFish 4 build 66 - javax.websocket.* package: TOTD #190

    - by arungupta
    This blog has published a few blogs on using JSR 356 Reference Implementation (Tyrus) integrated in GlassFish 4 promoted builds. TOTD #183: Getting Started with WebSocket in GlassFish TOTD #184: Logging WebSocket Frames using Chrome Developer Tools, Net-internals and Wireshark TOTD #185: Processing Text and Binary (Blob, ArrayBuffer, ArrayBufferView) Payload in WebSocket TOTD #186: Custom Text and Binary Payloads using WebSocket TOTD #189: Collaborative Whiteboard using WebSocket in GlassFish 4 The earlier blogs created a WebSocket endpoint as: import javax.net.websocket.annotations.WebSocketEndpoint;@WebSocketEndpoint("websocket")public class MyEndpoint { . . . Based upon the discussion in JSR 356 EG, the package names have changed to javax.websocket.*. So the updated endpoint definition will look like: import javax.websocket.WebSocketEndpoint;@WebSocketEndpoint("websocket")public class MyEndpoint { . . . The POM dependency is: <dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.0-b09</version> </dependency> And if you are using GlassFish 4 build 66, then you also need to provide a dummy EndpointFactory implementation as: import javax.websocket.WebSocketEndpoint;@WebSocketEndpoint(value="websocket", factory=MyEndpoint.DummyEndpointFactory.class)public class MyEndpoint { . . .   class DummyEndpointFactory implements EndpointFactory {    @Override public Object createEndpoint() { return null; }  }} This is only interim and will be cleaned up in subsequent builds. But I've seen couple of complaints about this already and so this deserves a short blog. Have you been tracking the latest Java EE 7 implementations in GlassFish 4 promoted builds ?

    Read the article

  • WebSocket and Java EE 7 - Getting Ready for JSR 356 (TOTD #181)

    - by arungupta
    WebSocket is developed as part of HTML 5 specification and provides a bi-directional, full-duplex communication channel over a single TCP socket. It provides dramatic improvement over the traditional approaches of Polling, Long-Polling, and Streaming for two-way communication. There is no latency from establishing new TCP connections for each HTTP message. There is a WebSocket API and the WebSocket Protocol. The Protocol defines "handshake" and "framing". The handshake defines how a normal HTTP connection can be upgraded to a WebSocket connection. The framing defines wire format of the message. The design philosophy is to keep the framing minimum to avoid the overhead. Both text and binary data can be sent using the API. WebSocket may look like a competing technology to Server-Sent Events (SSE), but they are not. Here are the key differences: WebSocket can send and receive data from a client. A typical example of WebSocket is a two-player game or a chat application. Server-Sent Events can only push data data to the client. A typical example of SSE is stock ticker or news feed. With SSE, XMLHttpRequest can be used to send data to the server. For server-only updates, WebSockets has an extra overhead and programming can be unecessarily complex. SSE provides a simple and easy-to-use model that is much better suited. SSEs are sent over traditional HTTP and so no modification is required on the server-side. WebSocket require servers that understand the protocol. SSE have several features that are missing from WebSocket such as automatic reconnection, event IDs, and the ability to send arbitrary events. The client automatically tries to reconnect if the connection is closed. The default wait before trying to reconnect is 3 seconds and can be configured by including "retry: XXXX\n" header where XXXX is the milliseconds to wait before trying to reconnect. Event stream can include a unique event identifier. This allows the server to determine which events need to be fired to each client in case the connection is dropped in between. The data can span multiple lines and can be of any text format as long as EventSource message handler can process it. WebSockets provide true real-time updates, SSE can be configured to provide close to real-time by setting appropriate timeouts. OK, so all excited about WebSocket ? Want to convert your POJOs into WebSockets endpoint ? websocket-sdk and GlassFish 4.0 is here to help! The complete source code shown in this project can be downloaded here. On the server-side, the WebSocket SDK converts a POJO into a WebSocket endpoint using simple annotations. Here is how a WebSocket endpoint will look like: @WebSocket(path="/echo")public class EchoBean { @WebSocketMessage public String echo(String message) { return message + " (from your server)"; }} In this code "@WebSocket" is a class-level annotation that declares a POJO to accept WebSocket messages. The path at which the messages are accepted is specified in this annotation. "@WebSocketMessage" indicates the Java method that is invoked when the endpoint receives a message. This method implementation echoes the received message concatenated with an additional string. The client-side HTML page looks like <div style="text-align: center;"> <form action=""> <input onclick="send_echo()" value="Press me" type="button"> <input id="textID" name="message" value="Hello WebSocket!" type="text"><br> </form></div><div id="output"></div> WebSocket allows a full-duplex communication. So the client, a browser in this case, can send a message to a server, a WebSocket endpoint in this case. And the server can send a message to the client at the same time. This is unlike HTTP which follows a "request" followed by a "response". In this code, the "send_echo" method in the JavaScript is invoked on the button click. There is also a <div> placeholder to display the response from the WebSocket endpoint. The JavaScript looks like: <script language="javascript" type="text/javascript"> var wsUri = "ws://localhost:8080/websockets/echo"; var websocket = new WebSocket(wsUri); websocket.onopen = function(evt) { onOpen(evt) }; websocket.onmessage = function(evt) { onMessage(evt) }; websocket.onerror = function(evt) { onError(evt) }; function init() { output = document.getElementById("output"); } function send_echo() { websocket.send(textID.value); writeToScreen("SENT: " + textID.value); } function onOpen(evt) { writeToScreen("CONNECTED"); } function onMessage(evt) { writeToScreen("RECEIVED: " + evt.data); } function onError(evt) { writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data); } function writeToScreen(message) { var pre = document.createElement("p"); pre.style.wordWrap = "break-word"; pre.innerHTML = message; output.appendChild(pre); } window.addEventListener("load", init, false);</script> In this code The URI to connect to on the server side is of the format ws://<HOST>:<PORT>/websockets/<PATH> "ws" is a new URI scheme introduced by the WebSocket protocol. <PATH> is the path on the endpoint where the WebSocket messages are accepted. In our case, it is ws://localhost:8080/websockets/echo WEBSOCKET_SDK-1 will ensure that context root is included in the URI as well. WebSocket is created as a global object so that the connection is created only once. This object establishes a connection with the given host, port and the path at which the endpoint is listening. The WebSocket API defines several callbacks that can be registered on specific events. The "onopen", "onmessage", and "onerror" callbacks are registered in this case. The callbacks print a message on the browser indicating which one is called and additionally also prints the data sent/received. On the button click, the WebSocket object is used to transmit text data to the endpoint. Binary data can be sent as one blob or using buffering. The HTTP request headers sent for the WebSocket call are: GET ws://localhost:8080/websockets/echo HTTP/1.1Origin: http://localhost:8080Connection: UpgradeSec-WebSocket-Extensions: x-webkit-deflate-frameHost: localhost:8080Sec-WebSocket-Key: mDbnYkAUi0b5Rnal9/cMvQ==Upgrade: websocketSec-WebSocket-Version: 13 And the response headers received are Connection:UpgradeSec-WebSocket-Accept:q4nmgFl/lEtU2ocyKZ64dtQvx10=Upgrade:websocket(Challenge Response):00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 The headers are shown in Chrome as shown below: The complete source code shown in this project can be downloaded here. The builds from websocket-sdk are integrated in GlassFish 4.0 builds. Would you like to live on the bleeding edge ? Then follow the instructions below to check out the workspace and install the latest SDK: Check out the source code svn checkout https://svn.java.net/svn/websocket-sdk~source-code-repository Build and install the trunk in your local repository as: mvn install Copy "./bundles/websocket-osgi/target/websocket-osgi-0.3-SNAPSHOT.jar" to "glassfish3/glassfish/modules/websocket-osgi.jar" in your GlassFish 4 latest promoted build. Notice, you need to overwrite the JAR file. Anybody interested in building a cool application using WebSocket and get it running on GlassFish ? :-) This work will also feed into JSR 356 - Java API for WebSocket. On a lighter side, there seems to be less agreement on the name. Here are some of the options that are prevalent: WebSocket (W3C API, the URL is www.w3.org/TR/websockets though) Web Socket (HTML5 Demos - html5demos.com/web-socket) Websocket (Jenkins Plugin - wiki.jenkins-ci.org/display/JENKINS/Websocket%2BPlugin) WebSockets (Used by Mozilla - developer.mozilla.org/en/WebSockets, but use WebSocket as well) Web sockets (HTML5 Working Group - www.whatwg.org/specs/web-apps/current-work/multipage/network.html) Web Sockets (Chrome Blog - blog.chromium.org/2009/12/web-sockets-now-available-in-google.html) I prefer "WebSocket" as that seems to be most common usage and used by the W3C API as well. What do you use ?

    Read the article

  • WebSocket Applications using Java: JSR 356 Early Draft Now Available (TOTD #183)

    - by arungupta
    WebSocket provide a full-duplex and bi-directional communication protocol over a single TCP connection. JSR 356 is defining a standard API for creating WebSocket applications in the Java EE 7 Platform. This Tip Of The Day (TOTD) will provide an introduction to WebSocket and how the JSR is evolving to support the programming model. First, a little primer on WebSocket! WebSocket is a combination of IETF RFC 6455 Protocol and W3C JavaScript API (still a Candidate Recommendation). The protocol defines an opening handshake and data transfer. The API enables Web pages to use the WebSocket protocol for two-way communication with the remote host. Unlike HTTP, there is no need to create a new TCP connection and send a chock-full of headers for every message exchange between client and server. The WebSocket protocol defines basic message framing, layered over TCP. Once the initial handshake happens using HTTP Upgrade, the client and server can send messages to each other, independent from the other. There are no pre-defined message exchange patterns of request/response or one-way between client and and server. These need to be explicitly defined over the basic protocol. The communication between client and server is pretty symmetric but there are two differences: A client initiates a connection to a server that is listening for a WebSocket request. A client connects to one server using a URI. A server may listen to requests from multiple clients on the same URI. Other than these two difference, the client and server behave symmetrically after the opening handshake. In that sense, they are considered as "peers". After a successful handshake, clients and servers transfer data back and forth in conceptual units referred as "messages". On the wire, a message is composed of one or more frames. Application frames carry payload intended for the application and can be text or binary data. Control frames carry data intended for protocol-level signaling. Now lets talk about the JSR! The Java API for WebSocket is worked upon as JSR 356 in the Java Community Process. This will define a standard API for building WebSocket applications. This JSR will provide support for: Creating WebSocket Java components to handle bi-directional WebSocket conversations Initiating and intercepting WebSocket events Creation and consumption of WebSocket text and binary messages The ability to define WebSocket protocols and content models for an application Configuration and management of WebSocket sessions, like timeouts, retries, cookies, connection pooling Specification of how WebSocket application will work within the Java EE security model Tyrus is the Reference Implementation for JSR 356 and is already integrated in GlassFish 4.0 Promoted Builds. And finally some code! The API allows to create WebSocket endpoints using annotations and interface. This TOTD will show a simple sample using annotations. A subsequent blog will show more advanced samples. A POJO can be converted to a WebSocket endpoint by specifying @WebSocketEndpoint and @WebSocketMessage. @WebSocketEndpoint(path="/hello")public class HelloBean {     @WebSocketMessage    public String sayHello(String name) {         return "Hello " + name + "!";     }} @WebSocketEndpoint marks this class as a WebSocket endpoint listening at URI defined by the path attribute. The @WebSocketMessage identifies the method that will receive the incoming WebSocket message. This first method parameter is injected with payload of the incoming message. In this case it is assumed that the payload is text-based. It can also be of the type byte[] in case the payload is binary. A custom object may be specified if decoders attribute is specified in the @WebSocketEndpoint. This attribute will provide a list of classes that define how a custom object can be decoded. This method can also take an optional Session parameter. This is injected by the runtime and capture a conversation between two endpoints. The return type of the method can be String, byte[] or a custom object. The encoders attribute on @WebSocketEndpoint need to define how a custom object can be encoded. The client side is an index.jsp with embedded JavaScript. The JSP body looks like: <div style="text-align: center;"> <form action="">     <input onclick="say_hello()" value="Say Hello" type="button">         <input id="nameField" name="name" value="WebSocket" type="text"><br>    </form> </div> <div id="output"></div> The code is relatively straight forward. It has an HTML form with a button that invokes say_hello() method and a text field named nameField. A div placeholder is available for displaying the output. Now, lets take a look at some JavaScript code: <script language="javascript" type="text/javascript"> var wsUri = "ws://localhost:8080/HelloWebSocket/hello";     var websocket = new WebSocket(wsUri);     websocket.onopen = function(evt) { onOpen(evt) };     websocket.onmessage = function(evt) { onMessage(evt) };     websocket.onerror = function(evt) { onError(evt) };     function init() {         output = document.getElementById("output");     }     function say_hello() {      websocket.send(nameField.value);         writeToScreen("SENT: " + nameField.value);     } This application is deployed as "HelloWebSocket.war" (download here) on GlassFish 4.0 promoted build 57. So the WebSocket endpoint is listening at "ws://localhost:8080/HelloWebSocket/hello". A new WebSocket connection is initiated by specifying the URI to connect to. The JavaScript API defines callback methods that are invoked when the connection is opened (onOpen), closed (onClose), error received (onError), or a message from the endpoint is received (onMessage). The client API has several send methods that transmit data over the connection. This particular script sends text data in the say_hello method using nameField's value from the HTML shown earlier. Each click on the button sends the textbox content to the endpoint over a WebSocket connection and receives a response based upon implementation in the sayHello method shown above. How to test this out ? Download the entire source project here or just the WAR file. Download GlassFish4.0 build 57 or later and unzip. Start GlassFish as "asadmin start-domain". Deploy the WAR file as "asadmin deploy HelloWebSocket.war". Access the application at http://localhost:8080/HelloWebSocket/index.jsp. After clicking on "Say Hello" button, the output would look like: Here are some references for you: WebSocket - Protocol and JavaScript API JSR 356: Java API for WebSocket - Specification (Early Draft) and Implementation (already integrated in GlassFish 4 promoted builds) Subsequent blogs will discuss the following topics (not necessary in that order) ... Binary data as payload Custom payloads using encoder/decoder Error handling Interface-driven WebSocket endpoint Java client API Client and Server configuration Security Subprotocols Extensions Other topics from the API Capturing WebSocket on-the-wire messages

    Read the article

  • Logging WebSocket Frames using Chrome Developer Tools, Net-internals and Wireshark (TOTD #184)

    - by arungupta
    TOTD #183 explained how to build a WebSocket-driven application using GlassFish 4. This Tip Of The Day (TOTD) will explain how do view/debug on-the-wire messages, or frames as they are called in WebSocket parlance, over this upgraded connection. This blog will use the application built in TOTD #183. First of all, make sure you are using a browser that supports WebSocket. If you recall from TOTD #183 then WebSocket is combination of Protocol and JavaScript API. A browser supporting WebSocket, or not, means they understand your web pages with the WebSocket JavaScript. caniuse.com/websockets provide a current status of WebSocket support in different browsers. Most of the major browsers such as Chrome, Firefox, Safari already support WebSocket for the past few versions. As of this writing, IE still does not support WebSocket however its planned for a future release. Viewing WebSocket farmes require special settings because all the communication happens over an upgraded HTTP connection over a single TCP connection. If you are building your application using Java, then there are two common ways to debug WebSocket messages today. Other language libraries provide different mechanisms to log the messages. Lets get started! Chrome Developer Tools provide information about the initial handshake only. This can be viewed in the Network tab and selecting the endpoint hosting the WebSocket endpoint. You can also click on "WebSockets" on the bottom-right to show only the WebSocket endpoints. Click on "Frames" in the right panel to view the actual frames being exchanged between the client and server. The frames are not refreshed when new messages are sent or received. You need to refresh the panel by clicking on the endpoint again. To see more detailed information about the WebSocket frames, you need to type "chrome://net-internals" in a new tab. Click on "Sockets" in the left navigation bar and then on "View live sockets" to see the page. Select the box with the address to your WebSocket endpoint and see some basic information about connection and bytes exchanged between the client and the endpoint. Clicking on the blue text "source dependency ..." shows more details about the handshake. If you are interested in viewing the exact payload of WebSocket messages then you need a network sniffer. These tools are used to snoop network traffic and provide a lot more details about the raw messages exchanged over the network. However because they provide lot more information so they need to be configured in order to view the relevant information. Wireshark (nee Ethereal) is a pretty standard tool for sniffing network traffic and will be used here. For this blog purpose, we'll assume that the WebSocket endpoint is hosted on the local machine. These tools do allow to sniff traffic across the network though. Wireshark is quite a comprehensive tool and we'll capture traffic on the loopback address. Start wireshark, select "loopback" and click on "Start". By default, all traffic information on the loopback address is displayed. That includes tons of TCP protocol messages, applications running on your local machines (like GlassFish or Dropbox on mine), and many others. Specify "http" as the filter in the top-left. Invoke the application built in TOTD #183 and click on "Say Hello" button once. The output in wireshark looks like Here is a description of the messages exchanged: Message #4: Initial HTTP request of the JSP page Message #6: Response returning the JSP page Message #16: HTTP Upgrade request Message #18: Upgrade request accepted Message #20: Request favicon Message #22: Responding with favicon not found Message #24: Browser making a WebSocket request to the endpoint Message #26: WebSocket endpoint responding back You can also use Fiddler to debug your WebSocket messages. How are you viewing your WebSocket messages ? Here are some references for you: JSR 356: Java API for WebSocket - Specification (Early Draft) and Implementation (already integrated in GlassFish 4 promoted builds) TOTD #183 - Getting Started with WebSocket in GlassFish Subsequent blogs will discuss the following topics (not necessary in that order) ... Binary data as payload Custom payloads using encoder/decoder Error handling Interface-driven WebSocket endpoint Java client API Client and Server configuration Security Subprotocols Extensions Other topics from the API

    Read the article

  • Collaborative Whiteboard using WebSocket in GlassFish 4 - Text/JSON and Binary/ArrayBuffer Data Transfer (TOTD #189)

    - by arungupta
    This blog has published a few blogs on using JSR 356 Reference Implementation (Tyrus) as its integrated in GlassFish 4 promoted builds. TOTD #183: Getting Started with WebSocket in GlassFish TOTD #184: Logging WebSocket Frames using Chrome Developer Tools, Net-internals and Wireshark TOTD #185: Processing Text and Binary (Blob, ArrayBuffer, ArrayBufferView) Payload in WebSocket TOTD #186: Custom Text and Binary Payloads using WebSocket One of the typical usecase for WebSocket is online collaborative games. This Tip Of The Day (TOTD) explains a sample that can be used to build such games easily. The application is a collaborative whiteboard where different shapes can be drawn in multiple colors. The shapes drawn on one browser are automatically drawn on all other peer browsers that are connected to the same endpoint. The shape, color, and coordinates of the image are transfered using a JSON structure. A browser may opt-out of sharing the figures. Alternatively any browser can send a snapshot of their existing whiteboard to all other browsers. Take a look at this video to understand how the application work and the underlying code. The complete sample code can be downloaded here. The code behind the application is also explained below. The web page (index.jsp) has a HTML5 Canvas as shown: <canvas id="myCanvas" width="150" height="150" style="border:1px solid #000000;"></canvas> And some radio buttons to choose the color and shape. By default, the shape, color, and coordinates of any figure drawn on the canvas are put in a JSON structure and sent as a message to the WebSocket endpoint. The JSON structure looks like: { "shape": "square", "color": "#FF0000", "coords": { "x": 31.59999942779541, "y": 49.91999053955078 }} The endpoint definition looks like: @WebSocketEndpoint(value = "websocket",encoders = {FigureDecoderEncoder.class},decoders = {FigureDecoderEncoder.class})public class Whiteboard { As you can see, the endpoint has decoder and encoder registered that decodes JSON to a Figure (a POJO class) and vice versa respectively. The decode method looks like: public Figure decode(String string) throws DecodeException { try { JSONObject jsonObject = new JSONObject(string); return new Figure(jsonObject); } catch (JSONException ex) { throw new DecodeException("Error parsing JSON", ex.getMessage(), ex.fillInStackTrace()); }} And the encode method looks like: public String encode(Figure figure) throws EncodeException { return figure.getJson().toString();} FigureDecoderEncoder implements both decoder and encoder functionality but thats purely for convenience. But the recommended design pattern is to keep them in separate classes. In certain cases, you may even need only one of them. On the client-side, the Canvas is initialized as: var canvas = document.getElementById("myCanvas");var context = canvas.getContext("2d");canvas.addEventListener("click", defineImage, false); The defineImage method constructs the JSON structure as shown above and sends it to the endpoint using websocket.send(). An instant snapshot of the canvas is sent using binary transfer with WebSocket. The WebSocket is initialized as: var wsUri = "ws://localhost:8080/whiteboard/websocket";var websocket = new WebSocket(wsUri);websocket.binaryType = "arraybuffer"; The important part is to set the binaryType property of WebSocket to arraybuffer. This ensures that any binary transfers using WebSocket are done using ArrayBuffer as the default type seem to be blob. The actual binary data transfer is done using the following: var image = context.getImageData(0, 0, canvas.width, canvas.height);var buffer = new ArrayBuffer(image.data.length);var bytes = new Uint8Array(buffer);for (var i=0; i<bytes.length; i++) { bytes[i] = image.data[i];}websocket.send(bytes); This comprehensive sample shows the following features of JSR 356 API: Annotation-driven endpoints Send/receive text and binary payload in WebSocket Encoders/decoders for custom text payload In addition, it also shows how images can be captured and drawn using HTML5 Canvas in a JSP. How could this be turned in to an online game ? Imagine drawing a Tic-tac-toe board on the canvas with two players playing and others watching. Then you can build access rights and controls within the application itself. Instead of sending a snapshot of the canvas on demand, a new peer joining the game could be automatically transferred the current state as well. Do you want to build this game ? I built a similar game a few years ago. Do somebody want to rewrite the game using WebSocket APIs ? :-) Many thanks to Jitu and Akshay for helping through the WebSocket internals! Here are some references for you: JSR 356: Java API for WebSocket - Specification (Early Draft) and Implementation (already integrated in GlassFish 4 promoted builds) Subsequent blogs will discuss the following topics (not necessary in that order) ... Error handling Interface-driven WebSocket endpoint Java client API Client and Server configuration Security Subprotocols Extensions Other topics from the API

    Read the article

  • Websocket handshake response not forwarded from TCP to client

    - by Saharsh
    I am trying to create a websocket server. I can see the websocket client's opening handhshake. My response to it is received by the client laptop (I can see this on wireshark). So the TCP connection has been established. But the client (a chrome websocket client extension) does not receive the handshake packet. What could be a possible reason for TCP to not forward the handshake to the client or for the client to not be able to read the TCP message? Client handshake: GET HTTP/1.1 Upgrade: websocket Connection:Upgrade Cache-Control:no-cache Host:192.168.0.101 Origin:http://www.websocket.org Pragma:no-cache Sec-WebSocket-Extensions:permessage-deflate; client_max_window_bits, x-webkit-deflate-frame Sec-WebSocket-Key: qrmw/m+BoZije6h9HYKmVw== Sec-WebSocket-Version:13 Upgrade:websocket Server Response: HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: jj1g5Io57m9ks8cme3jkbyo2asc= Access-Control-Allow-Origin: http://www.websocket.org Server: xyz Sec-WebSocket-Extensions: Thanks!

    Read the article

  • Browser-based MMOs (WebGL, WebSocket)

    - by Alon Gubkin
    Do you think it is technically possible to write a fully-fledged 3D MMO client with Browser JavaScript - WebGL for graphics, and WebSocket for Networking? Do you think future MMOs (and games generally) will wrriten with WebGL? Does today's JavaScript performance allow this? Let's say your development team was you as a developer, and another model creator (artist). Would you use a library like SceneJS for the game, or write straight WebGL? If you would use a library, but not SceneJS, please specify which. UPDATE (September 2012): RuneScape, which is a very popular 3D browser-based MMORPG that used Java Applets so far has announced that it will use HTML5 for their client (source). Java (left) and HTML5 (right)

    Read the article

  • Browser-based MMOs (WebGL, WebSocket)

    - by Alon
    Do you think it is techniclly possible to write a fully-fledged 3D MMO client with Browser JavaScript - WebGL for graphics, and WebSocket for Networking? Do you think future MMOs (and games generally) will wrriten with WebGL? Does today's JavaScript performance allow this? Let's say your development team was you as a developer, and another model creator (artist). Would you use a library like SceneJS for the game, or write straight WebGL? If you would use a library, but not SceneJS, please specify which. Thanks!

    Read the article

  • Processing Text and Binary (Blob, ArrayBuffer, ArrayBufferView) Payload in WebSocket - (TOTD #185)

    - by arungupta
    The WebSocket API defines different send(xxx) methods that can be used to send text and binary data. This Tip Of The Day (TOTD) will show how to send and receive text and binary data using WebSocket. TOTD #183 explains how to get started with a WebSocket endpoint using GlassFish 4. A simple endpoint from that blog looks like: @WebSocketEndpoint("/endpoint") public class MyEndpoint { public void receiveTextMessage(String message) { . . . } } A message with the first parameter of the type String is invoked when a text payload is received. The payload of the incoming WebSocket frame is mapped to this first parameter. An optional second parameter, Session, can be specified to map to the "other end" of this conversation. For example: public void receiveTextMessage(String message, Session session) {     . . . } The return type is void and that means no response is returned to the client that invoked this endpoint. A response may be returned to the client in two different ways. First, set the return type to the expected type, such as: public String receiveTextMessage(String message) { String response = . . . . . . return response; } In this case a text payload is returned back to the invoking endpoint. The second way to send a response back is to use the mapped session to send response using one of the sendXXX methods in Session, when and if needed. public void receiveTextMessage(String message, Session session) {     . . .     RemoteEndpoint remote = session.getRemote();     remote.sendString(...);     . . .     remote.sendString(...);    . . .    remote.sendString(...); } This shows how duplex and asynchronous communication between the two endpoints can be achieved. This can be used to define different message exchange patterns between the client and server. The WebSocket client can send the message as: websocket.send(myTextField.value); where myTextField is a text field in the web page. Binary payload in the incoming WebSocket frame can be received if ByteBuffer is used as the first parameter of the method signature. The endpoint method signature in that case would look like: public void receiveBinaryMessage(ByteBuffer message) {     . . . } From the client side, the binary data can be sent using Blob, ArrayBuffer, and ArrayBufferView. Blob is a just raw data and the actual interpretation is left to the application. ArrayBuffer and ArrayBufferView are defined in the TypedArray specification and are designed to send binary data using WebSocket. In short, ArrayBuffer is a fixed-length binary buffer with no format and no mechanism for accessing its contents. These buffers are manipulated using one of the views defined by one of the subclasses of ArrayBufferView listed below: Int8Array (signed 8-bit integer or char) Uint8Array (unsigned 8-bit integer or unsigned char) Int16Array (signed 16-bit integer or short) Uint16Array (unsigned 16-bit integer or unsigned short) Int32Array (signed 32-bit integer or int) Uint32Array (unsigned 16-bit integer or unsigned int) Float32Array (signed 32-bit float or float) Float64Array (signed 64-bit float or double) WebSocket can send binary data using ArrayBuffer with a view defined by a subclass of ArrayBufferView or a subclass of ArrayBufferView itself. The WebSocket client can send the message using Blob as: blob = new Blob([myField2.value]);websocket.send(blob); where myField2 is a text field in the web page. The WebSocket client can send the message using ArrayBuffer as: var buffer = new ArrayBuffer(10);var bytes = new Uint8Array(buffer);for (var i=0; i<bytes.length; i++) { bytes[i] = i;}websocket.send(buffer); A concrete implementation of receiving the binary message may look like: @WebSocketMessagepublic void echoBinary(ByteBuffer data, Session session) throws IOException {    System.out.println("echoBinary: " + data);    for (byte b : data.array()) {        System.out.print(b);    }    session.getRemote().sendBytes(data);} This method is just printing the binary data for verification but you may actually be storing it in a database or converting to an image or something more meaningful. Be aware of TYRUS-51 if you are trying to send binary data from server to client using method return type. Here are some references for you: JSR 356: Java API for WebSocket - Specification (Early Draft) and Implementation (already integrated in GlassFish 4 promoted builds) TOTD #183 - Getting Started with WebSocket in GlassFish TOTD #184 - Logging WebSocket Frames using Chrome Developer Tools, Net-internals and Wireshark Subsequent blogs will discuss the following topics (not necessary in that order) ... Error handling Custom payloads using encoder/decoder Interface-driven WebSocket endpoint Java client API Client and Server configuration Security Subprotocols Extensions Other topics from the API

    Read the article

  • Web Sockets: Browser won't receive the message, complains about it not starting with 0x00 (byte)

    - by giggsey
    Here is my code: import java.net.*; import java.io.*; import java.util.*; import org.jibble.pircbot.*; public class WebSocket { public static int port = 12345; public static ArrayList<WebSocketClient> clients = new ArrayList<WebSocketClient>(); public static ArrayList<Boolean> handshakes = new ArrayList<Boolean>(); public static ArrayList<String> nicknames = new ArrayList<String>(); public static ArrayList<String> channels = new ArrayList<String>(); public static int indexNum; public static void main(String args[]) { try { ServerSocket ss = new ServerSocket(WebSocket.port); WebSocket.console("Created socket on port " + WebSocket.port); while (true) { Socket s = ss.accept(); WebSocket.console("New Client connecting..."); WebSocket.handshakes.add(WebSocket.indexNum,false); WebSocket.nicknames.add(WebSocket.indexNum,""); WebSocket.channels.add(WebSocket.indexNum,""); WebSocketClient p = new WebSocketClient(s,WebSocket.indexNum); Thread t = new Thread( p); WebSocket.clients.add(WebSocket.indexNum,p); indexNum++; t.start(); } } catch (Exception e) { WebSocket.console("ERROR - " + e.toString()); } } public static void console(String msg) { Date date = new Date(); System.out.println("[" + date.toString() + "] " + msg); } } class WebSocketClient implements Runnable { private Socket s; private int iAm; private String socket_res = ""; private String socket_host = ""; private String socket_origin = ""; protected String nick = ""; protected String ircChan = ""; WebSocketClient(Socket socket, int mynum) { s = socket; iAm = mynum; } public void run() { String client = s.getInetAddress().toString(); WebSocket.console("Connection from " + client); IRCclient irc = new IRCclient(iAm); Thread t = new Thread( irc ); try { Scanner in = new Scanner(s.getInputStream()); PrintWriter out = new PrintWriter(s.getOutputStream(),true); while (true) { if (! in.hasNextLine()) continue; String input = in.nextLine().trim(); if (input.isEmpty()) continue; // Lets work out what's wrong with our input if (input.length() > 3 && input.charAt(0) == 65533) { input = input.substring(2); } WebSocket.console("< " + input); // Lets work out if they authenticate... if (WebSocket.handshakes.get(iAm) == false) { checkForHandShake(input); continue; } // Lets check for NICK: if (input.length() > 6 && input.substring(0,6).equals("NICK: ")) { nick = input.substring(6); Random generator = new Random(); int rand = generator.nextInt(); WebSocket.console("I am known as " + nick); WebSocket.nicknames.set(iAm, "bo-" + nick + rand); } if (input.length() > 9 && input.substring(0,9).equals("CHANNEL: ")) { ircChan = "bo-" + input.substring(9); WebSocket.console("We will be joining " + ircChan); WebSocket.channels.set(iAm, ircChan); } if (! ircChan.isEmpty() && ! nick.isEmpty() && irc.started == false) { irc.chan = ircChan; irc.nick = WebSocket.nicknames.get(iAm); t.start(); continue; } else { irc.msg(input); } } } catch (Exception e) { WebSocket.console(e.toString()); e.printStackTrace(); } t.stop(); WebSocket.channels.remove(iAm); WebSocket.clients.remove(iAm); WebSocket.handshakes.remove(iAm); WebSocket.nicknames.remove(iAm); WebSocket.console("Closing connection from " + client); } private void checkForHandShake(String input) { // Check for HTML5 Socket getHeaders(input); if (! socket_res.isEmpty() && ! socket_host.isEmpty() && ! socket_origin.isEmpty()) { send("HTTP/1.1 101 Web Socket Protocol Handshake\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "WebSocket-Origin: " + socket_origin + "\r\n" + "WebSocket-Location: ws://" + socket_host + "/\r\n\r\n",false); WebSocket.handshakes.set(iAm,true); } return; } private void getHeaders(String input) { if (input.length() >= 8 && input.substring(0,8).equals("Origin: ")) { socket_origin = input.substring(8); return; } if (input.length() >= 6 && input.substring(0,6).equals("Host: ")) { socket_host = input.substring(6); return; } if (input.length() >= 7 && input.substring(0,7).equals("Cookie:")) { socket_res = "."; } /*input = input.substring(4); socket_res = input.substring(0,input.indexOf(" HTTP")); input = input.substring(input.indexOf("Host:") + 6); socket_host = input.substring(0,input.indexOf("\r\n")); input = input.substring(input.indexOf("Origin:") + 8); socket_origin = input.substring(0,input.indexOf("\r\n"));*/ return; } protected void send(String msg, boolean newline) { byte c0 = 0x00; byte c255 = (byte) 0xff; try { PrintWriter out = new PrintWriter(s.getOutputStream(),true); WebSocket.console("> " + msg); if (newline == true) msg = msg + "\n"; out.print(msg + c255); out.flush(); } catch (Exception e) { WebSocket.console(e.toString()); } } protected void send(String msg) { try { WebSocket.console(">> " + msg); byte[] message = msg.getBytes(); byte[] newmsg = new byte[message.length + 2]; newmsg[0] = (byte)0x00; for (int i = 1; i <= message.length; i++) { newmsg[i] = message[i - 1]; } newmsg[message.length + 1] = (byte)0xff; // This prints correctly..., apparently... System.out.println(Arrays.toString(newmsg)); OutputStream socketOutputStream = s.getOutputStream(); socketOutputStream.write(newmsg); } catch (Exception e) { WebSocket.console(e.toString()); } } protected void send(String msg, boolean one, boolean two) { try { WebSocket.console(">> " + msg); byte[] message = msg.getBytes(); byte[] newmsg = new byte[message.length+1]; for (int i = 0; i < message.length; i++) { newmsg[i] = message[i]; } newmsg[message.length] = (byte)0xff; // This prints correctly..., apparently... System.out.println(Arrays.toString(newmsg)); OutputStream socketOutputStream = s.getOutputStream(); socketOutputStream.write(newmsg); } catch (Exception e) { e.printStackTrace(); } } } class IRCclient implements Runnable { protected String nick; protected String chan; protected int iAm; boolean started = false; IRCUser irc; IRCclient(int me) { iAm = me; irc = new IRCUser(iAm); } public void run() { WebSocket.console("Connecting to IRC..."); started = true; irc.setNick(nick); irc.setVerbose(false); irc.connectToIRC(chan); } void msg(String input) { irc.sendMessage("#" + chan, input); } } class IRCUser extends PircBot { int iAm; IRCUser(int me) { iAm = me; } public void setNick(String nick) { this.setName(nick); } public void connectToIRC(String chan) { try { this.connect("irc.appliedirc.com"); this.joinChannel("#" + chan); } catch (Exception e) { WebSocket.console(e.toString()); } } public void onMessage(String channel, String sender,String login, String hostname, String message) { // Lets send this message to me WebSocket.clients.get(iAm).send(message); } } Whenever I try to send the message to the browser (via Web Sockets), it complains that it doesn't start with 0x00 (which is a byte). Any ideas? Edit 19/02 - Added the entire code. I know it's real messy and not neat, but I want to get it functioning first. Spend last two days trying to fix.

    Read the article

  • Weblogic domain scale up using EM Grid Control 11gR1

    - by dmitry.nefedkin(at)oracle.com
    As you know a weblogic domain consists of set of servers running independently or in a cluster mode, sharing the distributed resources. And in most environments weblogic  cluster consists of multiple managed servers running simultaneously and working together to provide increased scalability and reliability.  These servers can run on the same machine, or be located on different machines.  It's a common task to increase a cluster's capacity by adding new machines to the cluster to host the new server instances.  You can do it by manually installing weblogic binaries to the new host and use pack/unpack commands to add a managed server to this new host.  But with Enterprise Manager Grid Control 11gR1 (EMGC) there is  another way - Fusion Middleware Domain Scale Up  procedure. I'm going to show you how it works.Here is a picture of  my medrec_oradb weblogic domain, what is registered in EMGC. It contains an admin server and a cluster MedRecCluster with  the single managed server MS1. Both admin and managed servers are on the same host oel46-vmware, it's a virtual machine with OEL 4.6 that runs inside our Oracle VM infrastructure.  And here are the application deployments, note that couple of applications are deployed to the cluster.First of all I have to prepare a new machine that will host new managed sever of my cluster. I created new VM with OEL 5.4 using the corresponding Oracle VM template available in Oracle E-Delivery site for Oracle Linux and Oracle VM and named it wls1032. Next step is to install Oracle EM Grid Control 11gR1 Agent to this new host.  You can download it from the OTN page and install it manually,  or you can use Agent Installation Deployment procedure available in EMGC  (Deployments->Agent Installation->Install Agent). Anyway, when you agent is up and running on the new machine, you will see it in EMGC Console in the Targets->Hosts subtab.Now we are ready to scale up our weblogic domain. Click the Deployments tab in Oracle Enterprise Manager Grid Control, and then click Deployment Procedure. Select a Fusion Middleware Domain Scale Up procedure from the list, and click Schedule Deployment. The first page of the FMW Domain Scale Up Wizard is displayed and you can proceed with the deployment process.Select the domain from list, enter the working directory on the admin server host, and also fill the weblogic credentials for the administration server console and the OS credentials for the  admin server host.  Click Next button.  The next step allows you to configure you domain, to add a new manager server to the cluster you should select the cluster in the tree and click Add Server button. Select the newly added server in a tree, choose the target host and  enter the configuration details of your managed server. You can also add new machine and node manager details.  Please note that you cannot change the values in  Domain Location and Fusion Middleware Home fields, so these locations on the target host will be the same as for the admin server host.   Working directory on the target host should have enough free space to store FMW home binaries and domain configuration files.  In my experience the working directories should have at least 3 Gb of free space.  The last thing you should fill is the OS credentials for the target host. The next steps allows you to schedule the execution of the procedure, it is started immediately in my example. The last step is just a review the configuration for the domain scale up. Click Submit to launch the process. You can track the status of the procedure execution by selecting Deployments->Deployment Procedures->Procedure Completion Status in the EMGC Console.As you can see in the picture below, the procedure consists of the many steps, and I'm going to share my experience about the issues that I had at some of the steps. Please keep in mind that you can always continue the execution from the last successfully completed step by clicking Retry button.Check OUI Prerequisites  step may fail if the target host does  not pass prerequisites checks for Weblogic Server installation such as amount of RAM, linux packages installed, etc. Create FMW Clone Archive step may fail if you do not have enough free space in the working directory on the administration server host.Transfer cloning archive to targets  step  may fail if the EMGC agents on the admin server host or on target host are not secured.   You should secure the agent by issuing ./emctl secure agent  command from $AGENT_HOME/bin directory and entering the agent registration password.Both Transfer cloning archive to targets and Apply Clone at target hosts steps may fail if you do not have enough free space in the working directory on the target host. The most complicated issue I had on the Run Inventory Collection  step. The step failed and I noticed that the agent on the target server is also failed with the following error in the $AGENT_HOME/sysman/log/emagent.trc  log file:2010-12-28 11:50:34,310 Thread-2838952848 ERROR upload: Failed to upload file A0000008.xml: Fatal Error.Response received: 500|ORA-20603: The timezone of the multiagent target (/Farm_Localhost_MedRec_medrec_oradb/medrec_oradb,weblogic_domain)is not consistent with the timezone (America/Los_Angeles) reported by other agents.2010-12-28 11:50:34,310 Thread-2838952848 ERROR upload: 1 Failure(s) in a row or XML error for A0000008.xml, retcode = -6, we give up2010-12-28 11:50:35,552 Thread-2838952848 WARN  upload: FxferSend: received fatal error in header from repository: https://oel46-vmware:1159/em/uploadFATAL_ERROR::500|ORA-20603: The timezone of the multiagent target (/Farm_Localhost_MedRec_medrec_oradb/medrec_oradb,weblogic_domain)is not consistent with the timezone (America/Los_Angeles) reported by other agents.2010-12-28 11:50:35,552 Thread-2838952848 ERROR upload: number of fatal error exceeds the limit 32010-12-28 11:50:35,552 Thread-2838952848 ERROR upload: agent will shutdown now2010-12-28 11:50:35,552 Thread-2838952848 ERROR : Signalled to Exit with status 55. Too many fatal upload failures2010-12-28 11:50:35,552 Thread-2838952848 ERROR upload: 1 Failure(s) in a row or XML error for A0000008.xml, retcode = -6, we give up2010-12-28 11:50:35,552 Thread-3044607680 ERROR main: EMAgent abnormal terminatingI checked the timezone of my domain target inside EMGC repositoryselect timezone_regionfrom mgmt_targets where target_type = 'weblogic_domain'  and display_name = 'medrec_oradb'"TIMEZONE_REGION""America/Los_Angeles"Then checked the timezone of my agents and indeed, they differedselect target_name, timezone_region from mgmt_targets where type_display_name = 'Agent'"TARGET_NAME"    "TIMEZONE_REGION""oel46-vmware:3872"    "America/Los_Angeles""wls1032.imc.fors.ru:3872"    "America/New_York"So I had to change the timezone on the wls1032 host and propagate this changes to the agent and to the EMGC repository. Here was the steps:issued system-config-date command on wls1032.imc.fors.ru  and set timezone to "America/Los_Angeles"propagated the changes to the agent bu executing ./emctl resetTZ agent  command from $AGENT_HOME/bin directoryconnected to EMGC repository as sysman and executed the following PL/SQL block:   begin      mgmt_target.set_agent_tzrgn('wls1032.imc.fors.ru:3872','America/Los_Angeles');      commit;   end;After that I had to clear the pending uploads on wls1032.imc.fors.ru:  rm -r $AGENT_HOME/sysman/emd/state/*  rm -r $AGENT_HOME/sysman/emd/collection/*  rm -r $AGENT_HOME/sysman/emd/upload/*  rm $AGENT_HOME/sysman/emd/lastupld.xml  rm $AGENT_HOME/sysman/emd/agntstmp.txt  $AGENT_HOME/bin/emctl start agent  $AGENT_HOME/bin/emctl clearstate agentThe last part of this solution was to resync the agent in EMGC console by clicking Agent Resynchronization button (please leave "Unblock agent on successful completion of agent resynchronization" checkbox checked in the next screen).After that I issued ./emctl upload command from $AGENT_HOME/bin on the wls1032 host,  and my previous error disappeared,  but I catched another one: EMD upload error: Failed to upload file A0000004.xml: HTTP error.Response received: ERROR-400|Data will be rejected for upload from agent 'https://wls1032.imc.fors.ru:3872/emd/main/', max size limit for direct load exceeded [7544731/5242880]So the uploading XML file size was 7 Mb, and the limit on OMS was 5 Mb.  To increase the max file size limit to 20 Mb I had to connect to the OMS host and execute the following commands from $OMS_HOME/bin directory: ./emctl set property -name em.loader.maxDirectLoadFileSz -value 20971520 -module emoms ./emctl stop oms ./emctl start omsAfter that I issued ./emctl upload command from $AGENT_HOME/bin on the wls1032 one more time and it completed successfully.   The agent uploaded the configuration information to the EMGC  repository and I was able to see the results of my weblogic domain scale-up in EMGC Console.DeploymentsSo, now the weblogic cluster contains 2 managed servers located on the different hosts. This powerful feature of the Enterprise Manager Grid Control  is a part of  the WebLogic Server Management Pack Enterprise Edition.

    Read the article

  • Java SE 7 Update 4??????·???????G1 GC??????“WebLogic+WebSocket”??????????????????????WebLogic Server 12c Forum 2012?????

    - by ???02
    2012?4?????????Java SE 7 Update 4????????·??????(GC)????G1 GC??????????GC???????????? ???????Web??????????????????HTML5??????/???????????????????WebSocket??????????????????WebLogic Server?????????????????????????????? 2012?8????????WebLogic Server 12c Forum 2012???????????·?????????????????????????(???) Java SE 7 Update 4??????G1 GC???????? 2012?8????????WebLogic Server 12c Forum 2012??????????????????·???????????????????????Java EE 6??????????????????????????????????????WebLogic Server????????????????????·???????????????????Java SE 7 Update 4???????GC??HTML5??????1????WebSocket??????????·????????????????????? ?????? Fusion Middleware?????? ?????????????? ???? 2012?4???????Java SE 7 Update 4?????Mac OS X????????????????????????G1 GC?????????? Fusion Middleware?????? ???????????????????????G1 GC???????????????? ????????GC???????????????????????????????????????????????????????????????????????????????????????????·??????????????????????????·??????????GC????????????????1??GC???????????????????????????????? GC????????????????????????????GC??????????????????????GC????GC???????????????????????????????GC??????????????????????????????????????????????????????????????? ???64????????????????????JVM?????64????????????64????JVM????GB???????·????????????????????????GC????????????????GC????????????????????????????·????????????????GC?????????????????????????????????????????????????????????????????SLA????????????????????·?????????????? ????????????????????????Java SE 7 Update 4????????GC?G1 GC?? G1 GC????????????????????????????????????????????????????????????GC???????????????????????????(????????)??????????????????????????????????????????????????????????????????????????????????????????? ??????G1 GC??????????????????????????????????????????? ??G1 GC?????????????????????????????????????????????????????????????????????????????????????????GC?????????????????????64????JVM????????·???????????????????????????????????????GC??????? ???????????????????????? ????????????????????????????????????????????OutOfMemory???????????????????????????????? WebLogic Server 12c?Java SE 7??????????????G1 GC???????????WebLogic Server 11g(10.3.6)??????????????????????GC????????JVM??????????-XX:+UseG1 GC????????????????? HTML5?Web????/?????????WebSocket?????????????????? ?????? Fusion Middleware?????? ?????????? ?????? ?????? Fusion Middleware???????WebLogic Server??????·???????????????????????·?????????Near future of WebLogic / ????WebLogic???????????????Web??????????HTML5???? ????????IT????????????????????1???????·?????????????????????????????????????????????????????????????HTML5?? HTML5???????HTML????????????HTML???Web????????????????????????HTML5???????????????????????????????????????????????HTML5????????/???????????????????????????????????WebWorker?????????????????????????????Web Storage???????API??????HTML5??????????????HTML??????????? ???HTML5??????????????????????WebSocket????????Web????/?????????????????????????? WebSocket????????????????????????(???????)?HTTP????????????????WebSocket????????WebSocket????????????????????????HTTP????????????????????????Web????/??????????????????? WebSocket??????????“??????Web”???????????????????????????????????????????????????????????????1???????????????????????HTTP???????????????????????????????????Comet????HTTP???????????????????????????????WebSocket???????????????????????????????????????????????????????????????? ?????????WebSocket????????????????????????????????????????????????????? WebSocket???????????????????????????? ?????? WebSocket???????(RFC 6455) ?????(Proposed Standard)??? WebSocket API(JavaScript)??(W3C) ????(Last Call Working Draft)??????2012?6?14???? WebSocket API Java EE??(JSR-356) Review Ballot??? ???? Web???? Google Chrome 16?Mozilla Firefox 11?Internet Explorer 10(PP5)?Safari 6??? ???·????? Jetty?jWebSocket?node.js?GlassFish 3.x????? ????????????????(RFC 6455)?????????JavaScript??????????????????????Java EE????????JSR-356?????????????????????????·????????????????????????????·??????????????? ??????????Java???????????????GlassFish????????????????????(JSR-356)??????????????·???·???????????????? ?WebSocket?WebLogic Server ??????????????WebSocket??WebLogic Server???????????????????? WebSocket????HTML5?????????????????????????????????HTML5?????????????????????Java EE?????????HTML5????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ???????HTML5?????????????????????????????????? ????????????? ?????????????????????????????????????????????????????????????????????????????????????????????????????HTML5???????????Java EE??????????????????????????(???) ???????????????????????????????????????????????????????????????????????????????????Java EE?WebLogic?????????????????????????????????????????????????????

    Read the article

  • WebSocket support on mobile devices

    - by Marco W.
    For an Android multiplayer game's communication between players I'm using a WebSocket server and TooTallNate's Java library on the client side to enable WebSocket support in the Android app. So just to point it out clearly, WebSocket support in mobile browsers is not important to me. Unfortunately, users report that they're experiencing problems such as connection failures or unreceived messages. Is that a general problem of WebSockets on mobile devices (blocked ports, firewalls, mobile Internet connection) or is that probably a flaw in the client side code? Do you have experience with WebSocket client libraries such as the one above? I've just discovered autobahn.ws for Android - but I don't know if it's worth switching from my current library (see above). What about WAMP? Is WebSocket technology not exactly the adequate solution so that I should use the sub-protocol (?) WAMP?

    Read the article

  • How does Play recognize a particular websocket message?

    - by noncom
    I am looking at the websocket-chat example. It unveils much, but I still cannot get something. I understand how messages are received, processed and sent on the web page side. However, Play captures websocket messages by means of the receive method of an Akka actor. In the websocket-chat, there are several cases in this method, but I don't get, how does it know which websocket message should be mapped to which case. In fact, I don't understand the path that a websocket message follows upon entering Play's domain, how is it processed and how can different message types/kinds be sent from the webpage. I have not find any info or sources related to this. Could please someone explain this or point to some kind of a good reference? UPDATE: The link to the original example.

    Read the article

  • WebSocket API 1.1 released!

    - by Pavel Bucek
    Its my please to announce that JSR 356 – Java API for WebSocket maintenance release ballot vote finished with majority of “yes” votes (actually, only one eligible voter did not vote, all other votes were “yeses”). New release is maintenance release and it addresses only one issue:  WEBSOCKET_SPEC-226. What changed in the 1.1? Version 1.1 is fully backwards compatible with version 1.0, there are only two methods added to javax.websocket.Session: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 /** * Register to handle to incoming messages in this conversation. A maximum of one message handler per * native websocket message type (text, binary, pong) may be added to each Session. I.e. a maximum * of one message handler to handle incoming text messages a maximum of one message handler for * handling incoming binary messages, and a maximum of one for handling incoming pong * messages. For further details of which message handlers handle which of the native websocket * message types please see {@link MessageHandler.Whole} and {@link MessageHandler.Partial}. * Adding more than one of any one type will result in a runtime exception. * * @param clazz   type of the message processed by message handler to be registered. * @param handler whole message handler to be added. * @throws IllegalStateException if there is already a MessageHandler registered for the same native *                               websocket message type as this handler. */ public void addMessageHandler(Class<T> clazz, MessageHandler.Whole<T> handler); /** * Register to handle to incoming messages in this conversation. A maximum of one message handler per * native websocket message type (text, binary, pong) may be added to each Session. I.e. a maximum * of one message handler to handle incoming text messages a maximum of one message handler for * handling incoming binary messages, and a maximum of one for handling incoming pong * messages. For further details of which message handlers handle which of the native websocket * message types please see {@link MessageHandler.Whole} and {@link MessageHandler.Partial}. * Adding more than one of any one type will result in a runtime exception. * * * @param clazz   type of the message processed by message handler to be registered. * @param handler partial message handler to be added. * @throws IllegalStateException if there is already a MessageHandler registered for the same native *                               websocket message type as this handler. */ public void addMessageHandler(Class<T> clazz, MessageHandler.Partial<T> handler); Why do we need to add those methods? Short and not precise version: to support Lambda expressions as MessageHandlers. Longer and slightly more precise explanation: old Session#addMessageHandler method (which is still there and works as it worked till now) does rely on getting the generic parameter during the runtime, which is not (always) possible. The unfortunate part is that it works for some common cases and the expert group did not catch this issue before 1.0 release because of that. The issue is really clearly visible when Lambdas are used as message handlers: 1 2 3 session.addMessageHandler(message -> { System.out.println("### Received: " + message); }); There is no way for the JSR 356 implementation to get the type of the used Lambda expression, thus this call will always result in an exception. Since all modern IDEs do recommend to use Lambda expressions when possible and MessageHandler interfaces are single method interfaces, it basically just scream “use Lambdas” all over the place but when you do that, the application will fail during runtime. Only solution we currently have is to explicitly provide the type of registered MessageHandler. (There might be another sometime in the future when generic type reification is introduced, but that is not going to happen soon enough). So the example above will then be: 1 2 3 session.addMessageHandler(String.class, message -> { System.out.println("### Received: " + message); }); and voila, it works. There are some limitations – you cannot do 1 List<String>.class , so you will need to encapsulate these types when you want to use them in MessageHandler implementation (something like “class MyType extends ArrayList<String>”). There is no better way how to solve this issue, because Java currently does not provide good way how to describe generic types. The api itself is available on maven central, look for javax.websocket:javax.websocket-api:1.1. The reference implementation is project Tyrus, which implements WebSocket API 1.1 from version 1.8.

    Read the article

  • eventmachine on debian fails install via rubygems

    - by Max
    this has been killing me for the last 5 hours. I don't seem to be able to get eventmachine running on my debian box. here this output: $ gem install thin Building native extensions. This could take a while... ERROR: Error installing thin: ERROR: Failed to build gem native extension. /home/eventhub/.rvm/rubies/ruby-1.9.3-p125/bin/ruby extconf.rb checking for rb_trap_immediate in ruby.h,rubysig.h... no checking for rb_thread_blocking_region()... yes checking for inotify_init() in sys/inotify.h... yes checking for writev() in sys/uio.h... yes checking for rb_wait_for_single_fd()... yes checking for rb_enable_interrupt()... yes checking for rb_time_new()... yes checking for sys/event.h... no checking for epoll_create() in sys/epoll.h... yes creating Makefile make compiling kb.cpp cc1plus: warning: command line option "-Wdeclaration-after-statement" is valid for C/ObjC but not for C++ cc1plus: warning: command line option "-Wimplicit-function-declaration" is valid for C/ObjC but not for C++ In file included from project.h:149, from kb.cpp:20: binder.h:35: warning: type qualifiers ignored on function return type In file included from project.h:150, from kb.cpp:20: em.h:84: warning: type qualifiers ignored on function return type em.h:85: warning: type qualifiers ignored on function return type em.h:86: warning: type qualifiers ignored on function return type em.h:88: warning: type qualifiers ignored on function return type em.h:89: warning: type qualifiers ignored on function return type em.h:90: warning: type qualifiers ignored on function return type em.h:91: warning: type qualifiers ignored on function return type em.h:93: warning: type qualifiers ignored on function return type em.h:99: warning: type qualifiers ignored on function return type em.h:116: warning: type qualifiers ignored on function return type em.h:125: warning: type qualifiers ignored on function return type In file included from project.h:154, from kb.cpp:20: eventmachine.h:46: warning: type qualifiers ignored on function return type eventmachine.h:47: warning: type qualifiers ignored on function return type eventmachine.h:48: warning: type qualifiers ignored on function return type eventmachine.h:50: warning: type qualifiers ignored on function return type eventmachine.h:65: warning: type qualifiers ignored on function return type eventmachine.h:66: warning: type qualifiers ignored on function return type eventmachine.h:67: warning: type qualifiers ignored on function return type eventmachine.h:68: warning: type qualifiers ignored on function return type In file included from project.h:154, from kb.cpp:20: eventmachine.h:103: warning: type qualifiers ignored on function return type eventmachine.h:105: warning: type qualifiers ignored on function return type eventmachine.h:108: warning: type qualifiers ignored on function return type compiling rubymain.cpp cc1plus: warning: command line option "-Wdeclaration-after-statement" is valid for C/ObjC but not for C++ cc1plus: warning: command line option "-Wimplicit-function-declaration" is valid for C/ObjC but not for C++ In file included from project.h:149, from rubymain.cpp:20: binder.h:35: warning: type qualifiers ignored on function return type In file included from project.h:150, from rubymain.cpp:20: em.h:84: warning: type qualifiers ignored on function return type em.h:85: warning: type qualifiers ignored on function return type em.h:86: warning: type qualifiers ignored on function return type em.h:88: warning: type qualifiers ignored on function return type em.h:89: warning: type qualifiers ignored on function return type em.h:90: warning: type qualifiers ignored on function return type em.h:91: warning: type qualifiers ignored on function return type em.h:93: warning: type qualifiers ignored on function return type em.h:99: warning: type qualifiers ignored on function return type em.h:116: warning: type qualifiers ignored on function return type em.h:125: warning: type qualifiers ignored on function return type In file included from project.h:154, from rubymain.cpp:20: eventmachine.h:46: warning: type qualifiers ignored on function return type eventmachine.h:47: warning: type qualifiers ignored on function return type eventmachine.h:48: warning: type qualifiers ignored on function return type eventmachine.h:50: warning: type qualifiers ignored on function return type eventmachine.h:65: warning: type qualifiers ignored on function return type eventmachine.h:66: warning: type qualifiers ignored on function return type eventmachine.h:67: warning: type qualifiers ignored on function return type eventmachine.h:68: warning: type qualifiers ignored on function return type In file included from project.h:154, from rubymain.cpp:20: eventmachine.h:103: warning: type qualifiers ignored on function return type eventmachine.h:105: warning: type qualifiers ignored on function return type eventmachine.h:108: warning: type qualifiers ignored on function return type compiling ssl.cpp cc1plus: warning: command line option "-Wdeclaration-after-statement" is valid for C/ObjC but not for C++ cc1plus: warning: command line option "-Wimplicit-function-declaration" is valid for C/ObjC but not for C++ In file included from project.h:149, from ssl.cpp:23: binder.h:35: warning: type qualifiers ignored on function return type In file included from project.h:150, from ssl.cpp:23: em.h:84: warning: type qualifiers ignored on function return type em.h:85: warning: type qualifiers ignored on function return type em.h:86: warning: type qualifiers ignored on function return type em.h:88: warning: type qualifiers ignored on function return type em.h:89: warning: type qualifiers ignored on function return type em.h:90: warning: type qualifiers ignored on function return type em.h:91: warning: type qualifiers ignored on function return type em.h:93: warning: type qualifiers ignored on function return type em.h:99: warning: type qualifiers ignored on function return type em.h:116: warning: type qualifiers ignored on function return type em.h:125: warning: type qualifiers ignored on function return type In file included from project.h:154, from ssl.cpp:23: eventmachine.h:46: warning: type qualifiers ignored on function return type eventmachine.h:47: warning: type qualifiers ignored on function return type eventmachine.h:48: warning: type qualifiers ignored on function return type eventmachine.h:50: warning: type qualifiers ignored on function return type eventmachine.h:65: warning: type qualifiers ignored on function return type eventmachine.h:66: warning: type qualifiers ignored on function return type eventmachine.h:67: warning: type qualifiers ignored on function return type eventmachine.h:68: warning: type qualifiers ignored on function return type In file included from project.h:154, from ssl.cpp:23: eventmachine.h:103: warning: type qualifiers ignored on function return type eventmachine.h:105: warning: type qualifiers ignored on function return type eventmachine.h:108: warning: type qualifiers ignored on function return type compiling cmain.cpp cc1plus: warning: command line option "-Wdeclaration-after-statement" is valid for C/ObjC but not for C++ cc1plus: warning: command line option "-Wimplicit-function-declaration" is valid for C/ObjC but not for C++ In file included from project.h:149, from cmain.cpp:20: binder.h:35: warning: type qualifiers ignored on function return type In file included from project.h:150, from cmain.cpp:20: em.h:84: warning: type qualifiers ignored on function return type em.h:85: warning: type qualifiers ignored on function return type em.h:86: warning: type qualifiers ignored on function return type em.h:88: warning: type qualifiers ignored on function return type em.h:89: warning: type qualifiers ignored on function return type em.h:90: warning: type qualifiers ignored on function return type em.h:91: warning: type qualifiers ignored on function return type em.h:93: warning: type qualifiers ignored on function return type em.h:99: warning: type qualifiers ignored on function return type em.h:116: warning: type qualifiers ignored on function return type em.h:125: warning: type qualifiers ignored on function return type In file included from project.h:154, from cmain.cpp:20: eventmachine.h:46: warning: type qualifiers ignored on function return type eventmachine.h:47: warning: type qualifiers ignored on function return type eventmachine.h:48: warning: type qualifiers ignored on function return type eventmachine.h:50: warning: type qualifiers ignored on function return type eventmachine.h:65: warning: type qualifiers ignored on function return type eventmachine.h:66: warning: type qualifiers ignored on function return type eventmachine.h:67: warning: type qualifiers ignored on function return type eventmachine.h:68: warning: type qualifiers ignored on function return type In file included from project.h:154, from cmain.cpp:20: eventmachine.h:103: warning: type qualifiers ignored on function return type eventmachine.h:105: warning: type qualifiers ignored on function return type eventmachine.h:108: warning: type qualifiers ignored on function return type cmain.cpp:96: warning: type qualifiers ignored on function return type cmain.cpp:107: warning: type qualifiers ignored on function return type cmain.cpp:117: warning: type qualifiers ignored on function return type cmain.cpp:127: warning: type qualifiers ignored on function return type cmain.cpp:269: warning: type qualifiers ignored on function return type cmain.cpp:279: warning: type qualifiers ignored on function return type cmain.cpp:289: warning: type qualifiers ignored on function return type cmain.cpp:299: warning: type qualifiers ignored on function return type cmain.cpp:309: warning: type qualifiers ignored on function return type cmain.cpp:329: warning: type qualifiers ignored on function return type cmain.cpp:678: warning: type qualifiers ignored on function return type compiling em.cpp cc1plus: warning: command line option "-Wdeclaration-after-statement" is valid for C/ObjC but not for C++ cc1plus: warning: command line option "-Wimplicit-function-declaration" is valid for C/ObjC but not for C++ In file included from project.h:149, from em.cpp:23: binder.h:35: warning: type qualifiers ignored on function return type In file included from project.h:150, from em.cpp:23: em.h:84: warning: type qualifiers ignored on function return type em.h:85: warning: type qualifiers ignored on function return type em.h:86: warning: type qualifiers ignored on function return type em.h:88: warning: type qualifiers ignored on function return type em.h:89: warning: type qualifiers ignored on function return type em.h:90: warning: type qualifiers ignored on function return type em.h:91: warning: type qualifiers ignored on function return type em.h:93: warning: type qualifiers ignored on function return type em.h:99: warning: type qualifiers ignored on function return type em.h:116: warning: type qualifiers ignored on function return type em.h:125: warning: type qualifiers ignored on function return type In file included from project.h:154, from em.cpp:23: eventmachine.h:46: warning: type qualifiers ignored on function return type eventmachine.h:47: warning: type qualifiers ignored on function return type eventmachine.h:48: warning: type qualifiers ignored on function return type eventmachine.h:50: warning: type qualifiers ignored on function return type eventmachine.h:65: warning: type qualifiers ignored on function return type eventmachine.h:66: warning: type qualifiers ignored on function return type eventmachine.h:67: warning: type qualifiers ignored on function return type eventmachine.h:68: warning: type qualifiers ignored on function return type In file included from project.h:154, from em.cpp:23: eventmachine.h:103: warning: type qualifiers ignored on function return type eventmachine.h:105: warning: type qualifiers ignored on function return type eventmachine.h:108: warning: type qualifiers ignored on function return type em.cpp: In member function 'bool EventMachine_t::_RunEpollOnce()': em.cpp:578: warning: 'int rb_thread_select(int, fd_set*, fd_set*, fd_set*, timeval*)' is deprecated (declared at /home/eventhub/.rvm/rubies/ruby-1.9.3-p125/include/ruby-1.9.1/ruby/intern.h:379) em.cpp:578: warning: 'int rb_thread_select(int, fd_set*, fd_set*, fd_set*, timeval*)' is deprecated (declared at /home/eventhub/.rvm/rubies/ruby-1.9.3-p125/include/ruby-1.9.1/ruby/intern.h:379) em.cpp: In member function 'bool EventMachine_t::_RunSelectOnce()': em.cpp:974: warning: 'int rb_thread_select(int, fd_set*, fd_set*, fd_set*, timeval*)' is deprecated (declared at /home/eventhub/.rvm/rubies/ruby-1.9.3-p125/include/ruby-1.9.1/ruby/intern.h:379) em.cpp:974: warning: 'int rb_thread_select(int, fd_set*, fd_set*, fd_set*, timeval*)' is deprecated (declared at /home/eventhub/.rvm/rubies/ruby-1.9.3-p125/include/ruby-1.9.1/ruby/intern.h:379) em.cpp: At global scope: em.cpp:1057: warning: type qualifiers ignored on function return type em.cpp:1079: warning: type qualifiers ignored on function return type em.cpp:1265: warning: type qualifiers ignored on function return type em.cpp:1338: warning: type qualifiers ignored on function return type em.cpp:1510: warning: type qualifiers ignored on function return type em.cpp:1593: warning: type qualifiers ignored on function return type em.cpp:1856: warning: type qualifiers ignored on function return type em.cpp:1982: warning: type qualifiers ignored on function return type em.cpp:2046: warning: type qualifiers ignored on function return type em.cpp:2070: warning: type qualifiers ignored on function return type em.cpp:2142: warning: type qualifiers ignored on function return type em.cpp:2361: fatal error: error writing to /tmp/ccdlOK0T.s: No space left on device compilation terminated. make: *** [em.o] Error 1 Gem files will remain installed in /home/eventhub/.rvm/gems/ruby-1.9.3-p125/gems/eventmachine-1.0.1 for inspection. Results logged to /home/eventhub/.rvm/gems/ruby-1.9.3-p125/gems/eventmachine-1.0.1/ext/gem_make.out Any thoughts? I read a lot of different ways to solve this issue, but none of them worked. Thanks

    Read the article

  • How the websocket bi-directional concept work?

    - by GMsoF
    I think the main difference between websocket and http streaming (I am not refering to polling and long polling) is websocket allows bi-directional communication which is similar to usual raw socket programming. (above is my understanding, could be wrong, feel free to correct me.) My question is how the web client (browser) continue to send another request in the already-opened websocket? Usual http request will treat another request as new socket connection, but websocket does not, that is why I am confused, how it achieve that? It should be handled in Server side or Client (browser) side?

    Read the article

  • WebSocket@QCon NY

    - by reza_rahman
    QCon NY was held on June 10-14 at the New York Marriott/Brooklyn Bridge. Part of the QCon franchise, this is one of the most significant IT conferences in the greater NYC area. It was an honor to do a WebSocket (JSR 356) talk at the conference. Unfortunately, my schedule was such that I could only attend one day of the conference and did not really get a chance to attend many sessions or do much networking. I did get a chance to talk to fellow Oracle speakers Doug Clarke, Stephen Chin and Frederic Desbiens, which was great. My session, titled Building Java HTML5/WebSocket Applications with JSR 356 was very well attended and I had some excellent Q & A. The talk introduces HTML 5 WebSocket, overviews JSR 356, tours the API and ends with a small WebSocket demo on GlassFish 4. The slide deck for the talk is posted below. Building Java HTML5/WebSocket Applications with JSR 356 from Reza Rahman The demo code is posted on GitHub: https://github.com/m-reza-rahman/hello-websocket. Oracle hosted a reception in the evening which was very well attended. Later in the evening the QCon organizers hosted a very nice speakers' dinner at a local boutique restaurant with excellent atmosphere and good food.

    Read the article

  • WebSocket send extra information on connection

    - by MattDiPasquale
    Is there a way for a WebSocket client to send additional information on the initial connection to the WebSocket server? I'm asking because I want the client to send the user ID (string) to the server immediately. I don't want the client to send the user ID in the onopen callback. Why? Because it's faster and simpler. If the WebSocket API won't let you do this, why not? If there's no good reason, how could I suggest they add this simple feature?

    Read the article

  • Why Won't the WebSocket.onmessage Event Fire?

    - by SumWon
    Hey guys, After toying around with this for hours, I simply cannot find a solution. I'm working on a WebSocket server using "node.js" for a canvas based online game I'm developing. My game can connect to the server just fine, it accepts the handshake and can even send messages to the server. However, when the server responds to the client, the client doesn't get the message. No errors, nothing, it just sits there peacefully. I've ripped apart my code, trying everything I could think of to fix this, but alas, nothing. Here's a stripped copy of my server code. As I said before, the handshake works fine, the server receives data fine, but sending data back to the client does not. var sys = require('sys'), net = require('net'); var server = net.createServer(function (stream) { stream.setEncoding('utf8'); var shaken = 0; stream.addListener('connect', function () { sys.puts("New connection from: "+stream.remoteAddress); }); stream.addListener('data', function (data) { if (!shaken) { sys.puts("Handshaking..."); //Send handshake: stream.write( "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"+ "Upgrade: WebSocket\r\n"+ "Connection: Upgrade\r\n"+ "WebSocket-Origin: http://192.168.1.113\r\n"+ "WebSocket-Location: ws://192.168.1.71:7070/\r\n\r\n"); shaken=1; sys.puts("Handshaking complete."); } else { //Message received, respond with 'testMessage' var d = "testMessage"; var m = '\u0000' + d + '\uffff'; sys.puts("Sending '"+m+"' to client"); var result = stream.write(m, "utf8"); sys.puts(result); /* Result comes as true, meaning that it pushed the data out. Why isn't the client seeing it?!? */ } }); stream.addListener('end', function () { sys.puts("Connection closed!"); stream.end(); }); }); server.listen(7070); sys.puts("Server Started!");

    Read the article

  • Spotlight on GlassFish 4.1: #7 WebSocket Session Throttling and JMX Monitoring

    - by delabassee
    'Spotlight on GlassFish 4.1' is a series of posts that highlights specific enhancements of the upcoming GlassFish 4.1 release. It could be a new feature, a fix, a behavior change, a tip, etc. #7 WebSocket Session Throttling and JMX Monitoring GlassFish 4.1 embeds Tyrus 1.8.1 which is compliant with the Maintenance Release of JSR 356 ("WebSocket API 1.1"). This release also brings brings additional features to the WebSocket support in GlassFish. JMX Monitoring: Tyrus now exposes WebSocket metrics through JMX . In GF 4.1, the following message statistics are monitored for both sent and received messages: messages count messages count per second average message size smallest message size largest message size Those statistics are collected independently of the message type (global count) and per specific message type (text, binary and control message). In GF 4.1, Tyrus also monitors, and exposes through JMX, errors at the application and endpoint level. For more information, please check Tyrus JMX Monitoring Session Throttling To preserve resources on the server hosting websocket endpoints, Tyrus now offers ways to limit the number of open sessions. Those limits can be configured at different level: per whole application per endpoint per remote endpoint address (client IP address)   For more details, check Tyrus Session Throttling. The next entry will focus on Tyrus new clients-side features.

    Read the article

  • Spotlight on GlassFish 4.1: #6 Java API for WebSocket 1.1

    - by delabassee
    'Spotlight on GlassFish 4.1' is a series of posts that highlights specific enhancements of the upcoming GlassFish 4.1 release. It could be a new feature, a fix, a behavior change, a tip, etc. #6 Java API for WebSocket 1.1 JSR 356 (Java API for WebSocket) has recently passed the Maintenance Release ballot, this Maintenance Release fixes an important issue when Java SE 8 Lambdas are used (see here). GlassFish 4.1 will include an updated version of Tyrus (JSR 356 Reference Implementation) to bring the WebSocket API level to the latest version of the specification, i.e. WebSocket API for Java 1.1. It should be mentioned that the Tyrus version included in GlassFish 4.1 also brings additional features. Some of those will be highlighted in upcoming entries. https://blogs.oracle.com/theaquarium/resource/websocket_logo.png

    Read the article

  • Custom Text and Binary Payloads using WebSocket (TOTD #186)

    - by arungupta
    TOTD #185 explained how to process text and binary payloads in a WebSocket endpoint. In summary, a text payload may be received as public void receiveTextMessage(String message) {    . . . } And binary payload may be received as: public void recieveBinaryMessage(ByteBuffer message) {    . . .} As you realize, both of these methods receive the text and binary data in raw format. However you may like to receive and send the data using a POJO. This marshaling and unmarshaling can be done in the method implementation but JSR 356 API provides a cleaner way. For encoding and decoding text payload into POJO, Decoder.Text (for inbound payload) and Encoder.Text (for outbound payload) interfaces need to be implemented. A sample implementation below shows how text payload consisting of JSON structures can be encoded and decoded. public class MyMessage implements Decoder.Text<MyMessage>, Encoder.Text<MyMessage> {     private JsonObject jsonObject;    @Override    public MyMessage decode(String string) throws DecodeException {        this.jsonObject = new JsonReader(new StringReader(string)).readObject();               return this;    }     @Override    public boolean willDecode(String string) {        return true;    }     @Override    public String encode(MyMessage myMessage) throws EncodeException {        return myMessage.jsonObject.toString();    } public JsonObject getObject() { return jsonObject; }} In this implementation, the decode method decodes incoming text payload to MyMessage, the encode method encodes MyMessage for the outgoing text payload, and the willDecode method returns true or false if the message can be decoded. The encoder and decoder implementation classes need to be specified in the WebSocket endpoint as: @WebSocketEndpoint(value="/endpoint", encoders={MyMessage.class}, decoders={MyMessage.class}) public class MyEndpoint { public MyMessage receiveMessage(MyMessage message) { . . . } } Notice the updated method signature where the application is working with MyMessage instead of the raw string. Note that the encoder and decoder implementations just illustrate the point and provide no validation or exception handling. Similarly Encooder.Binary and Decoder.Binary interfaces need to be implemented for encoding and decoding binary payload. Here are some references for you: JSR 356: Java API for WebSocket - Specification (Early Draft) and Implementation (already integrated in GlassFish 4 promoted builds) TOTD #183 - Getting Started with WebSocket in GlassFish TOTD #184 - Logging WebSocket Frames using Chrome Developer Tools, Net-internals and Wireshark TOTD #185: Processing Text and Binary (Blob, ArrayBuffer, ArrayBufferView) Payload in WebSocket Subsequent blogs will discuss the following topics (not necessary in that order) ... Error handling Interface-driven WebSocket endpoint Java client API Client and Server configuration Security Subprotocols Extensions Other topics from the API

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >