HTML5客户端通过在html5 websocket客户端中提供客户端来减少编程人员的工作量。学习如何将这个html5 websocket客户端与服务器一起使用java将对许多程序员都有好处。
我想要创建一个HTML5 client与java服务器通信的示例,但是我无法找到如何实现它的方法。有人能在上面放一盏灯吗?
参考资料:用html5演示c++客户机/服务器
我在http://java.dzone.com/articles/creating-websocket-chat上找到了一个演示,但它不适合我。
发布于 2012-10-20 00:42:06
我已经实现了一个简单的java服务器端示例,我们可以看看它。我首先创建一个ServerSocket,它侦听端口2005上的连接
public class WebsocketServer {
public static final int MASK_SIZE = 4;
public static final int SINGLE_FRAME_UNMASKED = 0x81;
private ServerSocket serverSocket;
private Socket socket;
public WebsocketServer() throws IOException {
serverSocket = new ServerSocket(2005);
connect();
}
private void connect() throws IOException {
System.out.println("Listening");
socket = serverSocket.accept();
System.out.println("Got connection");
if(handshake()) {
listenerThread();
}
}正如websocket协议的RFC标准中所定义的,当客户端通过websocket连接时,必须进行握手。让我们看一下握手()方法,它非常难看,因此将逐步遍历它:第一部分读取客户端握手。
private boolean handshake() throws IOException {
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//This hashmap will be used to store the information given to the server in the handshake
HashMap<String, String> keys = new HashMap<>();
String str;
//Reading client handshake, handshake ends with CRLF which is again specified in the RFC, so we keep on reading until we hit ""...
while (!(str = in.readLine()).equals("")) {
//Split the string and store it in our hashmap
String[] s = str.split(": ");
System.out.println(str);
if (s.length == 2) {
keys.put(s[0], s[1]);
}
}客户端握手看起来像这样(这是chrome给我的22.0.1229.94米版本),根据RFC -第1.2节!
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:2005
Origin: null
Sec-WebSocket-Key: PyvrecP0EoFwVnHwC72ecA==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame现在,我们可以使用键映射在握手过程中创建相应的响应。引用RFC的话:
为了证明握手已被接收,服务器必须获取两条信息,并将它们组合起来形成响应。第一条信息来自客户端握手中的扣分-键头字段。对于此标头字段,服务器必须以字符串形式将此值与全局唯一标识符"258EAFA5-E914-47DA-95CA-C5AB0DC85B11“连接起来,这不太可能被不理解WebSocket协议的网络端点使用。然后在服务器的握手中返回此级联的SHA-1哈希(160位)( hash 64编码)。
所以这就是我们必须做的!用魔术字符串连接Sec-WebSocket-键,使用SHA-1哈希函数对其进行散列,并对其进行Base64 64编码。这就是下一个丑陋的班轮所做的。
String hash;
try {
hash = new BASE64Encoder().encode(MessageDigest.getInstance("SHA-1").digest((keys.get("Sec-WebSocket-Key") + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes()));
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
return false;
}然后,我们只返回新创建的散列到"Sec-WebSocket-Accept“字段中的预期响应。
//Write handshake response
out.write("HTTP/1.1 101 Switching Protocols\r\n"
+ "Upgrade: websocket\r\n"
+ "Connection: Upgrade\r\n"
+ "Sec-WebSocket-Accept: " + hash + "\r\n"
+ "\r\n");
out.flush();
return true;}
我们现在已经在客户端和服务器之间建立了一个成功的websocket连接。那么,现在怎么办?我们怎样才能让他们彼此交谈?我们可以从服务器发送消息到客户端。NB!从现在开始,我们不再使用HTTP与客户端对话。现在我们必须通信发送纯字节,并解释传入字节。那我们该怎么做呢?
来自服务器的消息必须是某种称为“框架”的格式,正如RFC -第5.6节中所描述的那样。当从服务器发送消息时,RFC声明第一个字节必须指定它是什么样的帧。一个值为0x81的字节告诉客户端,我们正在发送一条“单帧未隐藏的文本消息”,这基本上是一条文本消息。序列字节必须表示消息的长度。后面是数据或有效载荷。好吧好吧..。让我们实现这一点!
public void sendMessage(byte[] msg) throws IOException {
System.out.println("Sending to client");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream());
//first byte is kind of frame
baos.write(SINGLE_FRAME_UNMASKED);
//Next byte is length of payload
baos.write(msg.length);
//Then goes the message
baos.write(msg);
baos.flush();
baos.close();
//This function only prints the byte representation of the frame in hex to console
convertAndPrint(baos.toByteArray());
//Send the frame to the client
os.write(baos.toByteArray(), 0, baos.size());
os.flush();
}因此,要向客户机发送消息,我们只需调用sendMessage("Hello!“.getBytes())。
不太难吗?那么接收客户端的消息呢?嗯,有点复杂,但坚持住!
来自客户端的帧发送的结构几乎与服务器发送的帧相同。第一个字节是消息类型,第二个字节是有效负载长度。还有一个区别:接下来的四个字节表示一个掩码。什么是掩码,为什么来自客户端的消息被屏蔽,而服务器的消息不是?从RFC - 5.1节中,我们可以看到:
...a客户端必须屏蔽它发送给服务器的所有帧.服务器不能掩盖它发送给客户端的任何帧。
所以简单的答案是:我们必须这样做。你可能会问,我们为什么要这么做呢?我不是告诉过你读RFC吗?
向前移动,在帧中的四个字节掩码之后,蒙面有效载荷正在继续。还有一件事,客户端必须将帧中最左边的第9位设置为1,这样才能告诉服务器消息被屏蔽了(查看RFC中整洁的ASCII-art框架--第5.2节)。第9个左位对应于我们第二个字节中的最左位,但是嘿,这是我们的有效负载长度字节!这意味着来自我们客户端的所有消息的有效负载长度字节等于0b10000000 = 0x80 +实际有效负载长度。因此,要找出实际有效负载长度,我们必须从有效负载长度字节中减去0x80,或128,或0b10000000 (或任何其他数字系统),这是帧中的第二个字节。
哇,好吧..。听起来很复杂..。对于"TLDR"-guys,摘要:从第二个字节减去0x80以获得有效负载长度.
public String reiceveMessage() throws IOException {
//Read the first two bytes of the message, the frame type byte - and the payload length byte
byte[] buf = readBytes(2);
System.out.println("Headers:");
//Print them in nice hex to console
convertAndPrint(buf);
//And it with 00001111 to get four lower bits only, which is the opcode
int opcode = buf[0] & 0x0F;
//Opcode 8 is close connection
if (opcode == 8) {
//Client want to close connection!
System.out.println("Client closed!");
socket.close();
System.exit(0);
return null;
}
//Else I just assume it's a single framed text message (opcode 1)
else {
final int payloadSize = getSizeOfPayload(buf[1]);
System.out.println("Payloadsize: " + payloadSize);
//Read the mask, which is 4 bytes, and than the payload
buf = readBytes(MASK_SIZE + payloadSize);
System.out.println("Payload:");
convertAndPrint(buf);
//method continues below!现在我们已经阅读了整个消息,现在是时候揭开它,这样我们就可以理解有效载荷了。为了解开它,我创建了一个方法,它以掩码和有效载荷作为参数,并返回解码的有效载荷。因此,呼叫结束时:
buf = unMask(Arrays.copyOfRange(buf, 0, 4), Arrays.copyOfRange(buf, 4, buf.length));
String message = new String(buf);
return message;
}
}现在,unMask方法是相当甜蜜和微小的
private byte[] unMask(byte[] mask, byte[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = (byte) (data[i] ^ mask[i % mask.length]);
}
return data;
}getSizeOfPayload也是如此:
private int getSizeOfPayload(byte b) {
//Must subtract 0x80 from (unsigned) masked frames
return ((b & 0xFF) - 0x80);
}就这样!现在您应该能够使用纯套接字在两个方向上进行通信。为了完整起见,我将添加完整的Java类。它能够使用websockets与客户端接收和发送消息。
package javaapplication5;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import sun.misc.BASE64Encoder;
/**
*
* @author
* Anders
*/
public class WebsocketServer {
public static final int MASK_SIZE = 4;
public static final int SINGLE_FRAME_UNMASKED = 0x81;
private ServerSocket serverSocket;
private Socket socket;
public WebsocketServer() throws IOException {
serverSocket = new ServerSocket(2005);
connect();
}
private void connect() throws IOException {
System.out.println("Listening");
socket = serverSocket.accept();
System.out.println("Got connection");
if(handshake()) {
listenerThread();
}
}
private boolean handshake() throws IOException {
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
HashMap<String, String> keys = new HashMap<>();
String str;
//Reading client handshake
while (!(str = in.readLine()).equals("")) {
String[] s = str.split(": ");
System.out.println();
System.out.println(str);
if (s.length == 2) {
keys.put(s[0], s[1]);
}
}
//Do what you want with the keys here, we will just use "Sec-WebSocket-Key"
String hash;
try {
hash = new BASE64Encoder().encode(MessageDigest.getInstance("SHA-1").digest((keys.get("Sec-WebSocket-Key") + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes()));
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
return false;
}
//Write handshake response
out.write("HTTP/1.1 101 Switching Protocols\r\n"
+ "Upgrade: websocket\r\n"
+ "Connection: Upgrade\r\n"
+ "Sec-WebSocket-Accept: " + hash + "\r\n"
+ "\r\n");
out.flush();
return true;
}
private byte[] readBytes(int numOfBytes) throws IOException {
byte[] b = new byte[numOfBytes];
socket.getInputStream().read(b);
return b;
}
public void sendMessage(byte[] msg) throws IOException {
System.out.println("Sending to client");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream());
baos.write(SINGLE_FRAME_UNMASKED);
baos.write(msg.length);
baos.write(msg);
baos.flush();
baos.close();
convertAndPrint(baos.toByteArray());
os.write(baos.toByteArray(), 0, baos.size());
os.flush();
}
public void listenerThread() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
System.out.println("Recieved from client: " + reiceveMessage());
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
t.start();
}
public String reiceveMessage() throws IOException {
byte[] buf = readBytes(2);
System.out.println("Headers:");
convertAndPrint(buf);
int opcode = buf[0] & 0x0F;
if (opcode == 8) {
//Client want to close connection!
System.out.println("Client closed!");
socket.close();
System.exit(0);
return null;
} else {
final int payloadSize = getSizeOfPayload(buf[1]);
System.out.println("Payloadsize: " + payloadSize);
buf = readBytes(MASK_SIZE + payloadSize);
System.out.println("Payload:");
convertAndPrint(buf);
buf = unMask(Arrays.copyOfRange(buf, 0, 4), Arrays.copyOfRange(buf, 4, buf.length));
String message = new String(buf);
return message;
}
}
private int getSizeOfPayload(byte b) {
//Must subtract 0x80 from masked frames
return ((b & 0xFF) - 0x80);
}
private byte[] unMask(byte[] mask, byte[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = (byte) (data[i] ^ mask[i % mask.length]);
}
return data;
}
private void convertAndPrint(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString());
}
public static void main(String[] args) throws IOException, InterruptedException, NoSuchAlgorithmException {
WebsocketServer j = new WebsocketServer();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Write something to the client!");
j.sendMessage(br.readLine().getBytes());
}
}
}和html中的简单客户端:
<!DOCTYPE HTML>
<html>
<body>
<button type="button" onclick="connect();">Connect</button>
<button type="button" onclick="connection.close()">Close</button>
<form>
<input type="text" id="msg" />
<button type="button" onclick="sayHello();">Say Hello!</button>
<script>
var connection;
function connect() {
console.log("connection");
connection = new WebSocket("ws://localhost:2005/");
// Log errors
connection.onerror = function (error) {
console.log('WebSocket Error ');
console.log(error);
};
// Log messages from the server
connection.onmessage = function (e) {
console.log('Server: ' + e.data);
alert("Server said: " + e.data);
};
connection.onopen = function (e) {
console.log("Connection open...");
}
connection.onclose = function (e) {
console.log("Connection closed...");
}
}
function sayHello() {
connection.send(document.getElementById("msg").value);
}
function close() {
console.log("Closing...");
connection.close();
}
</script>
</body>
</html>希望这将澄清一些事情,并希望我对此有所启发:)
发布于 2012-10-03 08:21:48
从客户端使用jQuery ajax请求,在服务器端使用rest服务。
关于使用Rest创建war模块的讨论
第1条(休息服务)
这里是jQuery ajax
第2条(jQuery Ajax)
要编写Java套接字服务器,只需创建主程序
try
{
final ServerSocket ss = new ServerSocket(8001);
while (true)
{
final Socket s = ss.accept();
// @todo s.getInputStream();
}
}
catch (final IOException ex)
{
//
}它是服务器部分的主要级联
发布于 2012-10-17 20:36:45
试着读这个博客。它介绍了如何使用spring框架完成您的工作。如果还没有加入的话,应该尽快增加全面的支持。
http://keaplogik.blogspot.com.au/2012/05/atmosphere-websockets-comet-with-spring.html?m=1
我还建议查看一下春季发行说明。
https://stackoverflow.com/questions/12702305
复制相似问题