树莓派搭建TCP server并接受client的控制

思路

  • 监听从一级路由器下发的IP地址
  • client端登录
  • 如果是公网IP的话,则可以通过广域网上任何一台能上网的设备建立tcp长连接控制

Server端程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/python
import socket
import time
import sys
import RPi.GPIO as GPIO
host = '192.168.2.214'
port = 8080
print ('Start a socket:TCP...')
socket_tcp = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print ('TCP listen in port %s:%d'%(host,port))
host_addr = (host,port)
socket_tcp.bind(host_addr)
socket_tcp.listen(1)
socket_con,(client_ip,client_port) = socket_tcp.accept()
print('Connection accepted from:%s.'%client_ip)
socket_con.send('Here is RaspberryPi TCP server!')
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12,GPIO.OUT)
GPIO.setup(11,GPIO.OUT)
print ('Try to receiving a packege...')
while True:
try:
data = socket_con.recv(512)
if len(data)>0:
if data=='1':
GPIO.output (12,GPIO.HIGH)
GPIO.output (11,GPIO.HIGH)
elif data =='0':
GPIO.output (12,GPIO.LOW)
GPIO.output (11,GPIO.LOW)
socket_con.send(data)
time.sleep(1)
continue
except KeyboardInterrupt:
socket_tcp.close()
sys.exit(1)

client端程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/python
import socket
import time
import sys
#RPi's IP
SERVER_IP = "60.169.53.138" #raspberry ip address
SERVER_PORT = 8080 #port
print("Starting socket: TCP...")
server_addr = (SERVER_IP, SERVER_PORT)
socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
try:
print("Connecting to server @ %s:%d..." %(SERVER_IP, SERVER_PORT))
socket_tcp.connect(server_addr)
break
except KeyboardInterrupt or Exception:
print("Can't connect to server,try it latter!")
time.sleep(1)
continue
print("Please input 1 or 0 to turn on/off the led!")
while True:
try:
data = socket_tcp.recv(512)
if len(data)>0:
print("Received: %s" % data)
command=raw_input()
socket_tcp.send(command)
time.sleep(1)
continue
except KeyboardInterrupt or Exception:
socket_tcp.close()
socket_tcp=None
sys.exit(1)

作用是:远程开启或关闭Raspberry Pi上的11和12的LED

2017/1/21更新

多线程Server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import socket
import time
import sys
import RPi.GPIO as GPIO
import threading
#Please modify your Key!!
key = ''
host = ''
port =
#Please modify your Key!!
class MainClass():
def init(self):
print ('Start a socket:TCP...')
self.socket_tcp = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print ('TCP listen in port %s:%d'%(host,port))
self.host_addr = (host,port)
self.socket_tcp.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
self.socket_tcp.bind(self.host_addr)
self.socket_tcp.listen(50)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(12,GPIO.OUT)
try:
while True:
print ('Try to receiving...')
self.socket_con,self.addr = self.socket_tcp.accept()
client_ip,port = self.addr
print 'Client:',client_ip,'Port:',port
self.StartThreads()
time.sleep(0.1)
except KeyboardInterrupt:
self.socket_tcp.close()
time.sleep(2)
sys.exit()
def StartThreads(self):
thread = WorkThread(self.socket_con,self.addr)
thread.start()
def Error(self):
self.socket_tcp.close()
class WorkThread(threading.Thread):
def __init__(self,fork_sock_con,addr):
threading.Thread.__init__(self)
self.connect = fork_sock_con
self.ip,self.port = addr
time.sleep(0.1)
self.connect.send('Welcome To Raspberry Control Panel!\n')
self.event = threading.Event()
self.event.clear()
self.delay = 30
self.ifdo = True
def stop(self):
self.ifdo = False
def run(self):
try:
data = self.connect.recv(1024)
if not data:
self.ifdo = False
elif data == key:
time.sleep(0.1)
#self.connect.send('{\"M\":\"checkinok\",\"ID\":\"D0001\"}')
while self.ifdo:
self.event.wait(0.2)
data = self.connect.recv(1024)
if not data:
break
elif data == '1':
GPIO.output(12,True)
GPIO.output(11,True)
self.connect.send('The LED is On!\n')
elif data == '0':
GPIO.output(12,False)
GPIO.output(11,False)
self.connect.send('The LED is Off!\n')
elif data == 'checkout':
self.connect.send('Goodbye!')
break
else:
self.connect.send('Invilid Package!\n')
self.connect.close()
time.sleep(0.5)
print 'Disconnect with:%s'%(self.ip)
self.connect.close()
except socket.timeout:
print 'timeout!'
self.connect.close()
a = MainClass()
a.init()

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×