gpt4 book ai didi

javascript - 套接字连接只工作一次

转载 作者:行者123 更新时间:2023-12-04 19:36:43 25 4
gpt4 key购买 nike

我有一个用 java 编写的服务器,监听本地主机的一个端口。我正在尝试通过 Firefox 扩展连接到它。我可以发送请求并收到响应,但只能发送一次。然后,我不知道它为什么停止工作:我什至无法发送回复。

我认为流会在某个时候关闭,但我不知道为什么,因为我在 pump 界面中设置了参数,以便在完成时不关闭流...

这是我的代码:

const {components} = require("chrome");
const {NetUtil} = components.utils.import("resource://gre/modules/NetUtil.jsm");


var transport = null;
var outstream = null, instream = null;
var instream = components.classes["@mozilla.org/scriptableinputstream;1"]
.createInstance(components.interfaces.nsIScriptableInputStream);
var pump = components.classes["@mozilla.org/network/input-stream-pump;1"]
.createInstance(components.interfaces.nsIInputStreamPump);
var dataListener = null;

exports.connect = function(server, port, callback) {
transport = components.classes["@mozilla.org/network/socket-transport-service;1"]
.getService(components.interfaces.nsISocketTransportService)
.createTransport(["udp"], 0, server, port, null);
outstream = transport.openOutputStream(0, 0, 0);
stream = transport.openInputStream(0, 0, 0);

// Initialize
instream.init(stream);
pump.init(stream, -1, -1, 0, 0, false);

dataListener = {
receivedData: [],

onStartRequest: function(request, context) {
console.log("Connected to server");
},

onStopRequest: function(request, context, status) {
console.log("End of request");
},

onDataAvailable: function(request, context, inputStream, offset, count) {
var data = instream.read(count).replace(/\n/gm,'');
callback(data);
}
};
pump.asyncRead(dataListener, null);
}

exports.send = function(data) {
// Send data
var outData = data + '\n';
outstream.write(outData, outData.length);
}

exports.close = function(data) {
// Close stream
outstream.close();
stream.close();
}

编辑:java服务器代码

    public PluginConnection(int newPort) throws IOException {
serverSocket = new ServerSocket(this.port);
}

public void send(String message) {
if (this.clientSocket != null) {
out.println(message);
} else {
System.err.println("ERROR: message could not be sent because "
+ "connection is not established.");
}
}


public void open() {
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("ERROR: PIRServer could not open connection.");
e.printStackTrace();
}
}

public String getRequest() {
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
} catch (IOException e) {
System.err.println("ERROR: PIRServer could not open streams.");
e.printStackTrace();
}

String query = null;
try {
query = in.readLine();
} catch (IOException e) {
System.err.println("ERROR: could not open parse query.");
e.printStackTrace();
out.println("-1");
}
return query;
}

public void close() {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (clientSocket != null) {
clientSocket.close();
}
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}

有人知道解决办法吗?

最佳答案

这可能不是您正在寻找的那种答案,但我想我还是会推荐它。

您可以考虑使用 node.js 作为 Web 套接字服务器并使用 Firefox 中的 MozWebSocket,而不是使用 Java。它真的很好用。例如,在 Firefox 附加组件中:

if (typeof (MozWebSocket) != 'undefined') {
mysocket = new MozWebSocket(SOCKET_URL);
} else if (typeof (WebSocket) != 'undefined') {
mysocket = new WebSocket(SOCKET_URL);
} else {
alert("Can't get socket");
}
if (mysocket === null) {
alert("Can't get socket");
}

mysocket.onerror = function(event) {
/* error handling here */
};

mysocket.onopen = function() {
mysocket.send(JSON.stringify(msg));
mysocket.close();
}

在服务器端,这就是从 node.js 获取的全部内容:

var wss, http, server, wsServer, Client, fs, qs;

wss = require('node_modules/websocket/lib/WebSocketServer');
http = require('http');
fs = require('fs');
qs = require('querystring');

initializeServer();

wsServer.on('connect', function(connection) {
console.log((new Date()) + " Connection accepted.");
connection.on('message', function(message) {
if (message && message.type === 'utf8') {
var data = JSON.parse(message.utf8Data);
/* parse data here */
}
else {
console.log("Data is not utf8! Data = " + message);
}
});

connection.on('close', function(connection) {
console.log((new Date()) + " Client " + connection.remoteAddress + " disconnected.");
});
});

function initializeServer() {
server = http.createServer(function(request, response) {
});
server.listen(6969, function() {
console.log((new Date()) + " Server is listening on port 6969");
});

wsServer = new wss({
httpServer: server,
maxReceivedMessageSize: 0x800000,
autoAcceptConnections: true
});
}

关于javascript - 套接字连接只工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13395711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com