我正在尝试与另一个java程序和raspebrry pi连接的python应用程序。我的程序应该不断地从java和raspberry听,并能够响应。我不知道该怎么做。我正在使用几个线程,我可以向raspberry发送消息并在同一时间听java,但我不能听两个连接,这对我来说是必要的。
def startProgram(sock):
try:
sock.setblocking(False)
sock.settimeout(10)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.connect((JAVA_HOST, JAVA_PORT))
data = sock.recv(1024)
if (data == "abc\r\n"):
sock.sendall("abc otrzymane!!!\n")
global ROBOT_IP_ADDRESS
ROBOT_IP_ADDRESS = sys.argv[0] + "." + sys.argv[1] + "." + sys.argv[2] + "." + sys.argv[3]
threading.Thread(target=Steering, args=[order]).start()
threading.Thread(target=GetDistance, args=[sock]).start()
except:
sock.close()
finally:
return sock
//program starts here!
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock = startProgram(sock)
sock.listen(1)
sock.setblocking(0)
while 1:
conn, addr = sock.accept()
data = conn.recv(1024)
if (data == "camera\r\n"):
isCameraOn = ~isCameraOn
if isCameraOn == True:
SendOrder("camera_on")
else:
SendOrder("camera_off")
if(data == "order\r\n"):
order = data
这是我从java运行这个程序时执行的代码。它的功能代码是来自raspberry的收听信息:
def GetDistance(s):
s.bind((MY_IP_ADDRESS, FROM_ROBOT_PORT)) // EXCEPTION
s.listen(1)
while (True):
conn, addr = s.accept()
print('Connection address:', addr)
while 1:
data = conn.recv(BUFFER_SIZE_DISTANCE)
if not data: break
print("received data:", data)
conn.send(data) # echo
conn.close()
一般问题是socket。我不能创建两个套接字变量并同时在不同的端口监听,我不知道为什么。例外:
File "pythonScript.py", line 32, in GetDistance
s.bind((JAVA_HOST, FROM_ROBOT_PORT))
File "<string>", line 1, in bind
File "C:\jython2.5.0\Lib\socket.py", line 777, in bind
assert not self.sock_impl
AssertionError
我也不知道这个例外究竟意味着什么。