简体   繁体   English

Java和Python之间的套接字连接

[英]Socket connection between Java and Python

I have a simple Java Socket connected to my Python socketserver . 我有一个连接到我的Python socketserver的简单Java Socket In the client I want to send some data with size given in input: I want first sent an Integer with the size of the data and then the chunk of byte data. 在客户端中,我想发送输入中具有给定大小的一些数据:我想首先发送一个具有数据大小的Integer ,然后是byte数据块。

This is the client: 这是客户:

Integer size = 1234
Socket so = new Socket("10.151.0.248", 8000);
byte[] bytes = new byte[size];
DataOutputStream out = new DataOutputStream(so.getOutputStream());
out.writeInt(size);
out.write(bytes);

From the server side I would like to read the amount of data that will arrive first and then read the stream again till everything is received; 我想从服务器端读取将首先到达的数据量,然后再读取流,直到接收到所有内容为止; as final step I will send back an ACK to the client. 最后一步,我将向客户端发送一个ACK。

Here is the server: 这是服务器:

def handle(self):
    tot_data = []

    length = self.request.recv(4)
    size = struct.unpack("!i", length)[0]

    while len(tot_data) < size:
        data = self.request.recv(size - len(tot_data))
        if not data: break
        tot_data.append(data)

    data = bytes(b"ACK")
    # just send back the ack when transfer completed
    self.request.sendall(data)

I am able to retrieve the size of the data in the server, but when I try to read the actual data from the stream, just 4 bytes are retrieved again and then the recv() remain blocked waiting for more data. 我能够检索服务器中数据的大小,但是当我尝试从流中读取实际数据时,仅再次检索了4个字节,然后recv()仍然处于阻塞状态,等待更多数据。 I would like, first, to retrieve all the data, and then send back the ACK once the transfer is completed. 我想首先检索所有数据,然后在传输完成后发送回ACK。

Any suggestions? 有什么建议么?

There one problem in the handle method Python side. 在Python的handle方法中存在一个问题。 self.request.recv returns a string (for Python 2.x, it will be bytes for Python3), and you assemble strings in an array. self.request.recv返回一个字符串(对于Python 2.x,对于Python3,它将是字节),然后将字符串组装到数组中。 So the length of the array is just the number of chunks and not the number of bytes received. 因此,数组的长度仅是块的数量,而不是接收到的字节数。

You should write: 您应该写:

def handle(self):
    tot_data = b""

    length = self.request.recv(4)
    size = struct.unpack("!i", length)[0]
    while len(tot_data) < size:
        data = self.request.recv(size - len(tot_data))
        if not data: break
        tot_data += data

    data = bytes(b"ACK")
    # just send back the ack when transfer completed
    self.request.sendall(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM