下面是Server端的程序:# TCP-Serverimport socket
# 1. 創建 socket 對象
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 2. 將 socket 綁定到指定地址 (本機地址)address = ('192.168.1.102', 8889)
s.bind(address)
# 3. 接收連接請求# listen(backlog), The backlog argument specifies the maximum number of queued connections and should be at least 0;
# the maximum value is system-dependent (usually 5), the minimum value is forced to 0.
s.listen(5)
print 'Waiting for connection...'
# 4. 等待客戶請求壹個連接# 調用 accept 方法時,socket 會進入 "waiting" 狀態。
# accept方法返回壹個含有兩個元素的元組 (connection, address)。
# 第壹個元素 connection 是新的 socket 對象,服務器必須通過它與客戶通信;
# 第二個元素 address 是客戶的 Internet 地址。
new_s, addr = s.accept()
print 'Got connect from', addr
# 5. 處理:服務器和客戶端通過 send 和 recv 方法通信
command = ' '
print ('Please enter 1 to turn on the led, 2 to turn off the led,3 to disconnect the communication:')
while True:
command = raw_input()
new_s.send(command)
data = new_s.recv(512)
print data if data == 'Communication is disconnected':
break
# 6. 傳輸結束,關閉連接
new_s.close()
s.close()
接下來是Client端程序:
# TCP-Clientimport RPi.GPIO as GPIO
import time
import socket
address = ('192.168.1.102', 8889)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(address)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(27, GPIO.OUT)
GPIO.setup(17, GPIO.OUT)
GPIO.output(17, False)
GPIO.output(27, False)
while True:
command = s.recv(512)
if command == '1':
GPIO.output(27, True)
GPIO.output(17, False)
s.send('Command 1 received by client')
print "Command is ", command
elif command == '2':
GPIO.output(27, False)
GPIO.output(17, True)
s.send('Command 2 received by client')
print "Command is ", command
elif command == '3':
s.send('Communication is disconnected')
print "Command is ", command
break
else:
s.send('Please enter 1, 2 or 3')
print "Command is ", commands.close()
我們只需要在PC上運行Server的程序,在Raspberry Pi上運行Client的程序便可以控制LED的亮與熄了,很簡單。