data send by firefox tcp socket.send() can't retrive until close the socket

痴心易碎 提交于 2019-12-01 10:52:53

问题


I'm trying to send some data from Firefox to java desktop application .so my java class work as a server and Firefox script work as a client .when i test it using another java class which is client.java data successfully sent to server.java how ever when i use this firefox script to send data ,it actually connect to the server .but send("text"); doesn't work realtime .i mean sever shows received data when i close the socket socket.close(); . but i know there is no problem with server.java code.

this doesn't work

setTimeout(function(){socket.send("i'm firefox");},5000); // because socket isn't closed yet

this work

setTimeout(function(){socket.send("i'm firefox");},5000);
setTimeout(function(){socket.close();},6000); 

but i really don't want to close the socket because i want to send lot of data one by one.

here is the complete code tested on scratchpad [-browser]

var tcpSocket = Cc["@mozilla.org/tcp-socket;1"].createInstance(Ci.nsIDOMTCPSocket);
var socket = tcpSocket.open("127.0.0.1", 5000);

setTimeout(function(){socket.send("i'm firefox");},5000);
//setTimeout(function(){socket.close();},8000);// i'm firefox text retrieve by server when run this line / when close the socket.

i think java code isn't important.but here it is.

I'm asking why do i need to close the socket to send data ? and how can i send data without close the socket ?


update

i made a Gif to show my problem here you can see data not sending real time but when socket is closed all the data flushed .


回答1:


It's actually working. Your data is being received, but you're currently waiting for a new line to print your received messages:

while ((inputLine = in.readLine()) != null) {
    System.out.println("Server: " + inputLine);
    out.println(inputLine);

    if (inputLine.equals("Bye.")) {
        break;
    }
}

Which currently only happens when you close the socket. Just add a new line at the end of your messages and it will work as expected:

var tcpSocket = Cc["@mozilla.org/tcp-socket;1"].createInstance(Ci.nsIDOMTCPSocket);
var socket    = tcpSocket.open("127.0.0.1", 5000);

function sendMessage(msg){
    socket.send(msg + "\n");
}

setTimeout(function(){
    sendMessage("hi mark");
},3000);

setTimeout(function(){
    sendMessage("hi johnny");
},5000); 


来源:https://stackoverflow.com/questions/32556786/data-send-by-firefox-tcp-socket-send-cant-retrive-until-close-the-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!