我尝试使用tcp连接连接到交易平台,该平台在我的虚拟机上运行java。
我尝试使用以下代码:
import socket
TCP_IP = 'localhost'
TCP_PORT = 5333
BUFFER_SIZE = 1024
MESSAGE = "function=subscribe_portfolio_balance|item="xxxxxxxxxxxxxxxx"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print "received data:", data
代码无法正常工作,当我在终端上运行它时没有真正发生,没有错误消息,o消息都在......我在这里做错了什么?有没有办法构建代码,以便能够理解什么是错误的?
非常感谢
答案 0 :(得分:0)
有几件事可能会导致您的问题:
我建议您在https://docs.python.org/3/howto/sockets.html
查看Python Socket HOWTO指南我根据你的脚本嘲笑了一个快速测试。这对我有用,我做的唯一改变是修复消息字符串的引用。
<强> client.py 强>
import socket
TCP_IP = 'localhost'
TCP_PORT = 5333
BUFFER_SIZE = 1024
#note the outer ' around the message
MESSAGE = '"function=subscribe_portfolio_balance|item="xxxxxxxxxxxxxxxx"'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
print "sent data"
data = s.recv(BUFFER_SIZE)
print "recieved"
s.close()
print "received data:", data
<强> server.py 强>
import socket
TCP_IP = 'localhost'
TCP_PORT = 5333
BUFFER_SIZE = 1024
# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
serversocket.bind((TCP_IP, TCP_PORT))
# become a server socket
serversocket.listen(5)
while True:
# accept connections from outside
(clientsocket, address) = serversocket.accept()
# now do something with the clientsocket
data = clientsocket.recv(BUFFER_SIZE)
print "recieved: " + data
clientsocket.send(data)
clientsocket.close()