當前位置:編程學習大全網 - 編程語言 - socket通信為什麽能實現遠程控制

socket通信為什麽能實現遠程控制

對於樹莓派來說,可以通過ssh和電腦進行互聯,所以壹般的應用來說,不需要socket通信,只要打開ssh在樹莓派上運行寫好的Python或者C程序即可。但是,有的project需要多個sensor,如果僅僅通過打開多個ssh來運行不同程序,這樣sensor搜集的數據就不直觀,因此就需要在PC上建立壹個Server來和樹莓派通信,從而可以把所有sensor以及其他devices需要的信號都集中顯示在壹個PC端的程序上。如果會網頁編程的話,在樹莓派上建立壹個WEB服務器應該也很好實現這個功能。如果不會網頁編程,那只好使用socket通信了。最簡單的開始,也就是通過socket控制LED的亮與熄。

下面是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的亮與熄了,很簡單。

  • 上一篇:手勢輸入方式的手勢識別的原理
  • 下一篇:馬自達323正時皮帶記號怎麽對
  • copyright 2024編程學習大全網