2016-10-11 93 views
2

我想在python中编写套接字编程。每当客户端发送消息到服务器,LED应该开始闪烁。 我在PC上运行Raspberry Pi和客户端上的服务器程序。Python套接字编程和LED接口

这是在我的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

您正在比较字符串和数字。用'msg1 =“10”'替换你的服务器代码。如果这不起作用,您是否看到控制台中的“msg”? – Goufalite

+1

在你的'led_blink()'函数中是'while 1'循环。这是你的目的吗? – rocksteady

+0

是啊!用字符串替换后,我可以使LED闪烁。谢谢 – Arunkrishna

回答

0

您正在比较字符串"10"和数字10。将您的服务器代码更改为:

msg1 = "10" 
1

试试这个您的PC或覆盆子,然后相应地编辑:

#!/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位。

+0

这个答案解决了'led_blink()'函数中的无限循环:在出口可以调用'GPIO.cleanup()'! – Goufalite