扭曲过早关闭与Java套接字的连接

时间:2014-02-28 08:45:34

标签: java android python sockets twisted

我有以下服务器代码:

from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
from twisted.protocols.basic import NetstringReceiver

class Echo(NetstringReceiver):

    def stringReceived(self, request):
        print("stringReceived: %s" % request)

    def connectionLost(self, reason):
        print(reason)

此python客户端将重复使服务器通过单个连接按预期打印stringReceived:...消息:

import socket
import json
import sys
import time

HOST = 'localhost'    # The remote host
PORT = 6001              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
params = {
    "chat_id": sys.argv[1],
    "session": sys.argv[2],
}
send = '%s:%s,' % (len(json.dumps(params)), json.dumps(params))
s.send((send.strip()))
while 1:
    params = {
        "chat_id": sys.argv[1],
        "session": sys.argv[2],
        "message": sys.argv[3],
    }
    send = '%s:%s,' % (len(json.dumps(params)), json.dumps(params))
    s.send(send)
    time.sleep(1)
但是,这个java代码会输出stringReceived:...一次。在单个输出之后,我得到了错误,

  

[失败实例:回溯(没有帧失败)::连接已关闭   干净。

java socket代码是:

   public void sendMessage(final String message)
    {
        new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    if(socket == null) {
                        socket = new Socket("192.168.1.6", 6001);
                        Log.i("", "CREATING:"+socket.toString());
                    }
                    Log.i("", socket.toString());
                    OutputStream out = socket.getOutputStream();
                    PrintWriter output = new PrintWriter(out);
                    output.println(String.format("%d:%s,", message.length(), message));
                    output.flush();
                } catch (IOException e) {
                    Log.i("exc", e.getMessage());
                }
            }
        }).start();
    }

什么是过早关闭连接?这是唯一可以访问该套接字的类,这是使用它的唯一方法。

1 个答案:

答案 0 :(得分:2)

经过几天把头撞到墙上,我想通了。

NetstringReceiver要求输入为以下格式:

3:lol,

12:hello world!,

如果输入不符合netstring约定,则连接将丢失。

所以我的代码出了什么问题?

output.println(String.format("%d:%s,", message.length(), message));

println正在向消息中添加换行符,打破约定然后丢失连接。将此更改为print解决了我的问题。