要用LEGO建造自动化工厂,我尝试使用一个EV3块作为套接字服务器,另两个块作为客户端。如果一个客户端将数据发送到服务器,则服务器将处理该数据并为另一客户端发送适当的数据(语言:Python)。因此,必须将两个客户端同时连接到服务器。现在,我正在测试基本连接,触摸传感器的激活以及服务器和客户端之间的简单文本传输。下面的代码是我现在所做的。为了建立连接,现在我使用蓝牙网络共享将服务器和客户端连接到了互联网。现在,当我按下触摸传感器时,服务器程序停止并说
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
In ServerTwoReceive
received2 = str(sock2.recv(1024).decode())
OSError: [Errno 107] Transport endpoint is not connected
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
In ServerOneReceive
received1 = str(sock1.recv(1024).decode())
OSError: [Errno 107] Transport endpoint is not connected
Traceback (most recent call last):
ServerTest()
message1, message2 = ":Server sensor is pressed"
ValueError: too many values to unpack (expected 2)
我该如何解决这个问题?
最初,我尝试使用sock.listen(2)
但是它不允许同时连接。
服务器代码
#!/usr/bin/env python3
import datetime
import math
import socket
import sys
import threading
import traceback
from time import sleep, time
from ev3dev2.sensor.lego import TouchSensor
# Function to test two sockets in EV3Dev
# Test this function only when the EV3Dev is connected to an Android Mobile Phone using BlueTooth
def ServerTest():
global sock1, sock2, connection1, address1, connection2, address2, received1, received2, GConnect, client1, client2
global gintTotalCommand1, gintLastCommand1, glstCommand1
global gintTotalCommand2, gintLastCommand2, glstCommand2
global tspressed
EV31On = True
print('Connecting to the clients...')
print()
while EV31On:
sock1.bind(('', 8338))
sock1.listen(1)
sock2.bind(('', 8339))
sock2.listen(1)
client1 = []
client2 = []
while True:
connection1, address1 = sock1.accept()
connection2, address2 = sock2.accept()
client1 += [{'conn1': connection1, 'addr1': address1}]
client2 += [{'conn2': connection2, 'addr2': address2}]
add1 = str(address1)
add2 = str(address2)
print( 'connected by' + add1)
print()
print( 'connected by' + add2)
print()
connection1.settimeout(None)
connection2.settimeout(None)
connection1.sendall(":YouAreIn".encode())
connection2.sendall(":YouAreIn".encode())
thread_onereceive = threading.Thread(target=ServerOneReceive)
thread_onereceive.daemon = True
thread_onereceive.start()
thread_tworeceive = threading.Thread(target=ServerTwoReceive)
thread_tworeceive.daemon = True
thread_tworeceive.start()
thread_sensor = threading.Thread(target=sensorstatus)
thread_sensor.daemon = True
thread_sensor.start()
GConnect = True
while GConnect:
if gintLastCommand1 < gintTotalCommand1:
gintLastCommand1 += 1
received1 = glstCommand1[gintLastCommand1-1]
print("New message from client one:" + received1)
print()
elif gintLastCommand2 < gintTotalCommand2:
gintLastCommand2 += 1
received2 = glstCommand2[gintLastCommand2-1]
print("New message from client two:" + received2)
print()
elif tspressed:
connection1.sendall(":Server sensor is pressed".encode())
connection2.sendall(":Server sensor is pressed".encode())
else:
connection1.sendall(":server is closed".encode())
connection2.sendall(":server is closed".encode())
sys.exit()
def sensorstatus():
global tspressed
tspressed = False
while not ts.is_pressed:
pass
else:
tspressed = True
def ServerOneReceive():
global sock1, gintTotalCommand1, gintLastCommand1, glstCommand1, received1
received1 = str(sock1.recv(1024).decode())
gintTotalCommand1 +=1
glstCommand1.append(received1)
def ServerTwoReceive():
global sock2, gintTotalCommand2, gintLastCommand2, glstCommand2, received2
received2 = str(sock2.recv(1024).decode())
gintTotalCommand2 +=1
glstCommand2.append(received2)
#set numbers
gintLastCommand1 = 0
gintLastCommand2 = 0
gintTotalCommand1 = 0
gintTotalCommand2 = 0
glstCommand1 = []
glstCommand2 = []
ts = TouchSensor()
sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ServerTest()
客户代码
#!/usr/bin/env python3
import datetime
import traceback
import math
import socket
import threading
import sys
from time import sleep, time
from ev3dev2.button import Button
from ev3dev2.display import Display
from ev3dev2.led import Leds
from ev3dev2.sensor.lego import TouchSensor
from ev3dev2.sound import Sound
def Clientconnection():
global sock, received, connect, message, gintLastCommand, gintTotalCommand, glstCommand
sound = Sound()
HOST, PORT = "192.168.44.47", 8338
# HOST, PORT = "lhcdims.kmdns.net", 8338
try:
bolProgramEnd = False
while not bolProgramEnd:
# First Time Display is Slow, so display First
print('Connecting to Server ...')
print()
# Connect to server
try:
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(20)
sock.connect((HOST, PORT))
sock.settimeout(None)
while True:
try:
# Login
received = str(sock.recv(1024).decode())
if received == ":YouAreIn":
# Display Login Successful
print('Server Connected')
print()
except:
bolProgramEnd = True
except:
print('Login Failed')
print()
bolProgramEnd = True
client_thread = threading.Thread(target=ClientReceive)
client_thread.daemon = True
client_thread.start()
connect = True
while connect:
if gintLastCommand < gintTotalCommand:
gintLastCommand += 1
received = glstCommand[gintLastCommand-1]
if received == ":server is closed":
connect = False
bolProgramEnd = True
elif received == ":Server sensor is pressed":
sound.beep()
print('Server sensor is pressed')
print()
message = ":Client one just reacted"
thread_send = threading.Thread(target=ClientSend)
thread_send.daemon = True
thread_send.start()
else:
print('new message from server:' + received)
print()
else:
pass
else:
sys.exit()
finally:
pass
def ClientSend():
global sock, message
sock.sendall(message.encode())
def ClientReceive():
global gintLastCommand, gintTotalCommand, glstCommand, received
received = str(sock.recv(1024).decode())
gintTotalCommand +=1
glstCommand.append(received)
try:
gintLastCommand = 0
gintTotalCommand = 0
glstCommand = []
# main program
Clientconnection()
except:
logtime = str(time())
f=open("log" + logtime + ".txt",'a')
traceback.print_exc(file=f)
f.flush()
f.close()