我有一个用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);
}
}
有谁知道解决方案?