我试图在python中编写套接字编程。每当客户端向服务器发送消息时,LED应该开始闪烁。 我在Raspberry pi和PC上运行服务器程序。
以下是我的Pi上运行的服务器代码。
#!/usr/bin/python # This is server.py file
import socket # Import socket module
import time
import RPi.GPIO as GPIO # Import GPIO library
GPIO.setmode(GPIO.BOARD) # Use board pin numbering
GPIO.setup(11, GPIO.OUT) # Setup GPIO Pin 11 to OUT
GPIO.output(11,False) # Init Led off
def led_blink():
while 1:
print "got msg" # Debug msg
GPIO.output(11,True) # Turn on Led
time.sleep(1) # Wait for one second
GPIO.output(11,False) # Turn off Led
time.sleep(1) # Wait for one second
GPIO.cleanup()
s = socket.socket() # Create a socket object
host = "192.168.0.106" # Get local machine name
port = 12345 # Port
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
msg = c.recv(1024)
msg1 = 10
if msg == msg1:
led_blink()
print msg
c.close()
以下是在我的电脑上运行的客户端代码。
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = "192.168.0.106" # Get local machine name
port = 12345 # port
s.connect((host, port))
s.send('10')
s.close
我能够从客户端收到消息,但无法使LED闪烁。 对不起,我是新编码的人。我在硬件方面知识渊博,但在软件方面却不是。 请帮帮我。
答案 0 :(得分:1)
在您的PC或Raspberry上尝试此操作,然后进行相应编辑:
#!/usr/bin/python # This is server.py file
import socket # Import socket module
def led_blink(msg):
print "got msg", msg # Debug msg
s = socket.socket() # Create a socket object
host = "127.0.0.1" # Get local machine name
port = 12345 # Port
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print "Listening"
c, addr = s.accept() # Establish connection with client.
while True:
msg = c.recv(1024)
print 'Got connection from', addr
if msg == "Exit":
break
led_blink(msg)
c.close()
和
#!/usr/bin/python # This is client.py file
import socket, time # Import socket module
s = socket.socket() # Create a socket object
host = "127.0.0.1" # Get local machine name
port = 12345 # port
s.connect((host, port))
x=0
for x in range(10):
s.send('Message_'+str(x))
print x
time.sleep(2)
s.send('Exit')
s.close
请注意,我在同一台机器127.0.0.1上同时使用服务器和客户端,并删除了GPIO位,因为我没有它们。
答案 1 :(得分:0)
您正在将字符串"10"
与数字10
进行比较。将您的服务器代码更改为:
msg1 = "10"