在java客户端发送https请求后,Node.js服务器同时访问数据事件和结束事件

时间:2017-01-04 13:14:06

标签: javascript java node.js https

代码链接:https://github.com/jason51806/java_client/tree/master

客户代码:

public class SendClient {
    public static void main(String[] args) throws Exception {

    TrustManager[] trustAllCerts = new TrustManager[] {
        new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {  }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {  }

        }
    };

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    /*
    * end of the fix
    */
    URL url = new URL("https://localhost:8001");

    URLConnection con = url.openConnection();
    //HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setUseCaches(false);

    JSONObject writeJsonObj = new JSONObject();

    //BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
    //BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(con.getOutputStream()));
    writeJsonObj.put("msg","Hello server!");
    System.out.println(writeJsonObj.toString());
    printWriter.println(writeJsonObj);
    printWriter.flush();
    /*String text = writeJsonObj.toString();
    writer.write(text);
    writer.flush();*/

    while (true) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        System.out.println("--prepare to receive message");

        String line = null;

        line = bufferedReader.readLine();
        System.out.println("read something from server");
        System.out.println(line);
        JSONObject readJsonObj = new JSONObject(line);

        System.out.println(readJsonObj.toString());

        if (readJsonObj.has("test")) {
            System.out.println("Send the second message to server");
            printWriter.println(writeJsonObj);
            printWriter.println();
            printWriter.flush();
        }
    }
    }
}

服务器代码:

var https = require('https'); //Require module 
var fs = require('fs');

//varable declared
var Https_Options = null;   //Https server key and certificate
var Server = null;  //https server
var ServerInformation = null;   //Server's address and port
var ClientNumber = 0;   //current nunber of connected client
var num = 1;

Https_Options =
{
    key : fs.readFileSync('./hacksparrow-key.pem'),
    cert : fs.readFileSync('./hacksparrow-cert.pem'),
    allowHalfOpen : true
};

Server = https.createServer(Https_Options).listen(8001, "localhost", function() {
        ServerInformation = Server.address();
        console.log("Https server is running at "+ServerInformation.address+":"+ServerInformation.port);
    }    //end of https.createServer call back function
);    //end of https.createServer.listen

//Request listener, listening request event when client sending the request
//Call Back Function Description: "data", "close", "error" event

Server.on('request', function(req, res) {
    console.log("clients: "+ (ClientNumber++));
    //Data listener, litening is there any data sent from client
    //Call Back Function Description: The handler of "data" event
    req.on('data', function(chunk) {
        var ServerDataObj = null;   //the data received from client and also send this Obj as response to client
        var testobj = {};

        testobj = 
        {
            'test' : num++
        };

        //ServerDataObj = JSON.parse(chunk.toString());
        ServerDataObj = chunk.toString();
        console.log('server receive message' + ServerDataObj);
        res.write(JSON.stringify(testobj) + '\r\n');    //send back to client
        delete ServerDataObj;

    }    //end of event "data" call back function
    );    //end of event "data"

    req.on('end', function() {
            console.log("client end.");
        }    //end of event "end" call back function
    );  

    //listening close event
    //Call Back Function Description: Emmit whether the client socket close
    req.on('close', function() {
            console.log("client close.");
            --ClientNumber;
        }    //end of event "close" call back function
    );    //end of event "close"

    //Error listener, 
    //Call Back Function Description: if error happen, catch & print
    req.on('error', function(err) {
            console.error("req: "+err);
        }    //end of event "error" call back function
    );    //end of event "error"

}    //end of event "request" call back function
);    //end of event "request"

我使用PrintWiter在我的Java客户端代码上发送请求。

node.js服务器成功收到请求数据,但它触发了导致服务器无法再接收来自客户端的请求的结束处理程序。

我也尝试使用BufferedWriter和DataOutputStream将我的请求发送到服务器,但它们都有同样的问题。

  • 有没有办法不在服务器上触发结束处理程序并让客户端不断发送数据?
  • 或者在https?
  • 上的Java客户端和node.js服务器之间发送消息的任何其他方式

0 个答案:

没有答案