树莓派与阿里云服务器进行socket通信

首先约定好socket通信的端口号:7000
通过阿里服务器控制台打开对应端口
树莓派与阿里云服务器进行socket通信_第1张图片
注意:端口必须要在控制台打开,在服务器里打开端口无效!!

服务器端:

ip地址要写为服务器的内网ip
收到的数据是byte数组,所以要用decode解码,也可以指定字符集解码,默认是utf-8

import socket
HOST = '服务器的内网ip'
PORT = 7000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#绑定socket
s.bind((HOST, PORT))
#开始监听
s.listen(1)
print('Listening at port:',PORT)
conn, addr = s.accept()
print('Connected by', addr)
while True:
    data = conn.recv(1024)
    data = data.decode()
    if not data:
        break
    print('Received message:', data)
conn.close()
s.close()


树莓派端:
注意ip地址写服务器公网ip

import socket

HOST = '服务器公网ip' 
PORT = 7000
BUFSIZ =1024
ADDR = (HOST,PORT)

tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
     data1 = input('>')
     #data = str(data)
     if not data1:
         break
     tcpCliSock.send(data1.encode())
     data1 = tcpCliSock.recv(BUFSIZ)
     if not data1:
         break
     print(data1.decode('utf-8'))
tcpCliSock.close()

你可能感兴趣的:(linux,web)