我的项目基本上是使websocket实时与基于Java的服务器一起使用。我可能从网络论坛上提取的代码部分。基于Java的服务器在某种程度上可以与(非Web)应用程序客户端进行测试,但是其目的是使它能够与基于Web的客户端通信。
问题在于onmessage事件侦听器。在我的努力下,服务器可以成功地向Web客户端发送消息,而Web客户端可以读取该消息-但它只能一次运行。客户端中的onmessage事件一次最多只能收到来自服务器的一条消息。从字面上看,服务器必须重新启动,而浏览器必须重新启动,这不是我想要的。最终,我希望在与Java中的服务器进行通信时,使Web客户端实时更新,这类似于聊天程序。
我正在寻找确保维护事件侦听器的方法,但不确定如何执行此操作。另外,我不确定webclient是否需要在线程上,但也不确定如何执行此操作。
请访问我的github个人资料:https://github.com/russellbrown100?tab=repositories
-------------------------- Java服务器------------------ -----------
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package imageserver;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.io.ByteArrayOutputStream;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Base64;
import javax.xml.bind.DatatypeConverter;;
/**
*
* @author Russell Brown
*/
public class ImageServer {
public static ServerSocket server;
public static Socket clientSocket;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try
{
server = new ServerSocket(6666);
System.out.println("server created");
clientSocket = server.accept();
System.out.println("client accepted");
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
doHandShakeToInitializeWebSocketConnection(inputStream, outputStream);
int counter = 0;
while (true)
{
String string = "hello" + counter;
outputStream.write(encode(string));
counter++;
Thread.sleep(10);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static byte[] encode(String mess) throws IOException{
byte[] rawData = mess.getBytes();
int frameCount = 0;
byte[] frame = new byte[10];
frame[0] = (byte) 129;
if(rawData.length <= 125){
frame[1] = (byte) rawData.length;
frameCount = 2;
}else if(rawData.length >= 126 && rawData.length <= 65535){
frame[1] = (byte) 126;
int len = rawData.length;
frame[2] = (byte)((len >> 8 ) & (byte)255);
frame[3] = (byte)(len & (byte)255);
frameCount = 4;
}else{
frame[1] = (byte) 127;
int len = rawData.length;
frame[2] = (byte)((len >> 56 ) & (byte)255);
frame[3] = (byte)((len >> 48 ) & (byte)255);
frame[4] = (byte)((len >> 40 ) & (byte)255);
frame[5] = (byte)((len >> 32 ) & (byte)255);
frame[6] = (byte)((len >> 24 ) & (byte)255);
frame[7] = (byte)((len >> 16 ) & (byte)255);
frame[8] = (byte)((len >> 8 ) & (byte)255);
frame[9] = (byte)(len & (byte)255);
frameCount = 10;
}
int bLength = frameCount + rawData.length;
byte[] reply = new byte[bLength];
int bLim = 0;
for(int i=0; i<frameCount;i++){
reply[bLim] = frame[i];
bLim++;
}
for(int i=0; i<rawData.length;i++){
reply[bLim] = rawData[i];
bLim++;
}
return reply;
}
private static void doHandShakeToInitializeWebSocketConnection(InputStream inputStream, OutputStream outputStream) throws UnsupportedEncodingException {
String data = new Scanner(inputStream,"UTF-8").useDelimiter("\\r\\n\\r\\n").next();
Matcher get = Pattern.compile("^GET").matcher(data);
if (get.find()) {
Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data);
match.find();
byte[] response = null;
try {
response = ("HTTP/1.1 101 Switching Protocols\r\n"
+ "Connection: Upgrade\r\n"
+ "Upgrade: websocket\r\n"
+ "Sec-WebSocket-Accept: "
+ DatatypeConverter.printBase64Binary(
MessageDigest
.getInstance("SHA-1")
.digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
.getBytes("UTF-8")))
+ "\r\n\r\n")
.getBytes("UTF-8");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
outputStream.write(response, 0, response.length);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
}
}
private static void printInputStream(InputStream inputStream) throws IOException {
int len = 0;
byte[] b = new byte[1024];
//rawIn is a Socket.getInputStream();
while(true){
len = inputStream.read(b);
if(len!=-1){
byte rLength = 0;
int rMaskIndex = 2;
int rDataStart = 0;
//b[0] is always text in my case so no need to check;
byte data = b[1];
byte op = (byte) 127;
rLength = (byte) (data & op);
if(rLength==(byte)126) rMaskIndex=4;
if(rLength==(byte)127) rMaskIndex=10;
byte[] masks = new byte[4];
int j=0;
int i=0;
for(i=rMaskIndex;i<(rMaskIndex+4);i++){
masks[j] = b[i];
j++;
}
rDataStart = rMaskIndex + 4;
int messLen = len - rDataStart;
byte[] message = new byte[messLen];
for(i=rDataStart, j=0; i<len; i++, j++){
message[j] = (byte) (b[i] ^ masks[j % 4]);
}
System.out.println(new String(message));
b = new byte[1024];
}
}
}
}
---------------------------------- Web客户端---------- -------------------------------
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket Client</title>
<script type="text/javascript">
var wsocket;
function connect() {
wsocket = new WebSocket("ws://localhost:6666");
wsocket.onopen = onopen;
wsocket.onmessage = onmessage;
wsocket.onclose = onclose;
}
function onopen() {
document.writeln("opened");
}
function onmessage(event) {
document.writeln(event.data);
}
function onclose(e) {
document.writeln("closed");
}
window.addEventListener("load", connect, false);
</script>
</head>
<body>
</body>
</html>
我们将为您提供帮助。
请访问我的github个人资料:https://github.com/russellbrown100?tab=repositories
答案 0 :(得分:0)
解决方案:发现浏览器具有可以调试的开发工具。问题完全是IE的问题。已经删除了document.writeln并将响应添加到div元素,如下所示:
function onmessage(event) {
console.log(event.data);
var div = document.getElementsByName("mydiv")[0];
div.innerHTML += event.data;
// document.writeln(event.data);
}
感谢您的支持。