套接字连接只能工作一次

时间:2012-11-15 10:37:03

标签: javascript sockets firefox-addon

我用java编写的服务器监听localhost中的端口。我正在尝试通过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);
    }
}

有人知道解决方案吗?

1 个答案:

答案 0 :(得分:0)

这可能不是您正在寻找的那种答案,但我认为无论如何我都会建议。

您可以将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
    });
}