Get to know MDN better
This example shows you how to create a WebSocket API server using Oracle Java.
Although other server-side languages can be used to create a WebSocket server, this example uses Oracle Java to simplify the example code.
This server conforms to RFC 6455, so it only handles connections from Chrome version 16, Firefox 11, IE 10 and higher.
WebSockets communicate over a TCP (Transmission Control Protocol) connection. Java's ServerSocket class is located in the java.net package.
The ServerSocket constructor accepts a single parameter port of type int.
When you instantiate the ServerSocket class, it is bound to the port number you specified by the port argument.
Here's an implementation split into parts:
Returns an input stream for this socket.
java.net.Socket.getOutputStream()Returns an output stream for this socket.
Writes len bytes from the specified byte array starting at offset off to this output stream.
Reads up to len bytes of data from the input stream into an array of bytes.
Let us extend our example.
When a client connects to a server, it sends a GET request to upgrade the connection to a WebSocket from a simple HTTP request. This is known as handshaking.
Creating the response is easier than understanding why you must do it in this way.
You must,
After a successful handshake, client can send messages to the server, but now these are encoded.
If we send "abcdef", we get these bytes:
129 134 167 225 225 210 198 131 130 182 194 135129:
| 1 | 0 | 0 | 0 | 0x1=0001 |
FIN: You can send your message in frames, but now keep things simple. Opcode 0x1 means this is a text. Full list of Opcodes
134:
If the second byte minus 128 is between 0 and 125, this is the length of the message. If it is 126, the following 2 bytes (16-bit unsigned integer), if 127, the following 8 bytes (64-bit unsigned integer, the most significant bit MUST be 0) are the length.
Note: It can take 128 because the first bit is always 1.
167, 225, 225 and 210 are the bytes of the key to decode. It changes every time.
The remaining encoded bytes are the message.
decoded byte = encoded byte XOR (position of encoded byte BITWISE AND 0x3)th byte of key
Example in Java:
This page was last modified on Jul 26, 2024 by MDN contributors.
Your blueprint for a better internet.
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.