我试图在两个树莓派之间获得套接字连接。一个是客户端,另一个将返回客户端发送回客户端的任何内容。但是,当我执行它时,它返回客户端无法连接到服务器并在线路上停止" s.connect((serverMACAddress,port))"。
在这一天工作了一整天,没有任何地方,任何帮助表示赞赏。
这是客户端代码
import os
import platform
import socket
import sys
import json
def errorinput():
print("Server.py:")
print(" python3 ./client.py -a pull <query expressions>")
sys.exit(1)
def main():
#check if the arg is in right format
if len(sys.argv)<=1:
errorinput()
elif sys.argv[1] != "-a" :
errorinput()
elif len(sys.argv) >= 3:
if sys.argv[2] != "pull":
if sys.argv[3] != "-s" or sys.argv[5] != "-m":
errorinput()
else:
if len(sys.argv) !=4:
errorinput()
else:
errorinput()
#establish connection via bluetooth
serverMACAddress = 'xx:xx:xx:xx:xx:xx'
port = 3
size = 1024
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.connect((serverMACAddress,port))
data = "100" #send "100" to the server side as a test string
s.send (data)
receiveddata = s.recv(size)
s.close()
print (receiveddata)
if __name__ == "__main__":
main()
这里是服务器端代码(返回收到回客户端的任何消息)
import socket
import sys
import time
def main():
hostMACAddress = 'B8:27:EB:AA:49:DF'
port = 3
backlog = 5
size = 1024
s = None
try:
# Create a Bluetooth socket
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
# Bind the socket to the port
server_address = (hostMACAddress, port)
s.bind(server_address)
s.listen(backlog)
except s.error as e:
if s:
s.close()
print("Error: Cannot open socket: " + str(e))
sys.exit(1)
while True:
print('waiting for message')
client, client_address = s.accept()
data = s.recv(size)
if data:
client.send(data)
client.close()
if __name__ == "__main__":
main()