【问题标题】:Cannot Send data from Java Client to Python Server无法从 Java 客户端向 Python 服务器发送数据
【发布时间】:2017-05-02 20:23:12
【问题描述】:

我正在使用this method 从 Java 客户端发送数据并在 python 服务器上接收它。发送的数据是一个长度为 10 的简单字符串,但我无法在服务器端接收它。即使正确建立连接,它也会显示接收数据的空白输出。我检查了this 问题,所以我重新编程了我的服务器,首先接收 2 个字节,然后接收字符串,但它不起作用。谁能解释一下?我已经放了一些 cmets 来解释输出。

服务器.py

import socket
import time

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
print "Socket Created..."
s.bind((str(socket.INADDR_ANY), 2609))
print "Socket bound to INADDR_ANY with port 2609..."
s.listen(5)
print "Socket listening for connections..."
print "Waiting for client to connect..."
(c, remote_addr) = s.accept()

print "Connection From" + str(remote_addr) + " accepted"
rec = 'pppppppppppppppppp'

print 'rec = ' + rec               #Properly prints the initialized string
print 'lenght is ' + str(len(rec)) #prints length = 18
print "Receiving Data..."
leng = c.recv(2)
print "Data received..."
print leng                         #Does not print Anything

rec = c.recv(1024)

print rec                          #Does not print Anything

print 'lenght is ' + str(len(str(rec)))  #Length is 0
c.close()
print "Client socket closed..."
s.close()
print "Server Socket closed..."

输出

% python Server.py
Socket Created...
Socket bound to INADDR_ANY with port 2609...
Socket listening for connections...
Waiting for client to connect...
Connection From('192.168.43.7', 39100) accepted
rec = pppppppppppppppppp
lenght is 18
Receiving Data...
Data received...


lenght is 0
Client socket closed...
Server Socket closed...

【问题讨论】:

  • 您使用哪个版本的 Python?
  • @thatguy : python 2.7

标签: java python sockets tcp


【解决方案1】:

由于发送端的其余代码未知,我无法确定问题所在,但我可以想象可能有两个原因:

发送方

您使用link 中所述的代码。如果您没有收到任何内容,这可能表明 OutputStream 已被缓冲并且没有发送任何内容,尚未,尽管您调用了 write(...)。尝试flush()它,看看你是否收到了什么。

接收端

在 Python 3 中,recv 返回一个字节对象,如 documentation 中所述:

返回值是一个字节对象,表示接收到的数据。

在 Python 2 中,您会得到一个字符串,如 documentation 中所述:

返回值是一个字符串,表示接收到的数据。

现在,当您从编码为 UTF-8 的 Java 客户端发送字符串时,您应该在接收端使用 data.decode('utf-8') 再次解码字节或字符串以获得 Unicode 字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 2018-10-19
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    相关资源
    最近更新 更多