我正在尝试在运行以下代码的 chrome 扩展之间建立 websocket 连接:
if('WebSocket' in window){
connect('ws://localhost:8181/chat');
}
function connect(host) {
var ws = new WebSocket(host);
ws.onopen = function () {
alert('connected');
};
ws.onmessage = function (evt) {
alert('reveived data:'+evt.data);
};
ws.onclose = function () {
alert('socket closed');
};
};
和一个 Java 服务器。
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ServerThread extends Thread {
Socket socket = null;
int NumberOfThread;
Main Mainthread;
public ServerThread(Socket socket) {
super("ServerThread");
this.socket = socket;
}
@Override
public void run(){
try {
while(true){
BufferedReader SS_BF = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String temp = SS_BF.readLine();
System.out.println(temp);
}
} catch (IOException ex) {
suicide();
}
}
public void suicide(){
try {
/*this.socket.shutdownInput();
this.socket.shutdownOutput();
this.socket.close();*/
Mainthread.Coroner(NumberOfThread);
} catch (IOException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void identify(int n, Main m)throws IOException{
NumberOfThread=n;
Mainthread=m;
}
public void Send(String s)throws IOException{
PrintStream SSPS = new PrintStream(socket.getOutputStream());
SSPS.println(s);
System.out.println ("Sent text to CLIENT_" + NumberOfThread);
}
}
所以我可以建立连接,直到握手,然后什么也没有。客户端挂起或断开连接,但永远不会触发 onOpen 事件。
我希望我已经提供了足够的信息。谁能告诉我如何从 google chrome 扩展程序中的客户端和在桌面上运行的 java 服务器建立 websocket 连接?
提前致谢!斯莫列特。