socket实现公网服务端客户端通信(python版)

socket其实是可以走公网实现外部通信的,具体的流程如以下:

1.首先购买一个最便宜的阿里云(其它云大同小异)的云服务器,系统最好选择linux—ubuntu的系统,然后在系统里面上传你的服务器端python程序 ,要上传和下载文件可以用一个超好用工具 finalshell 真的特别好用,适合小白

json_send.py 主函数  注意:这里的ip地址填写分配给你的私有地址,主页面下方可以找到,端口可以自己通过安全组设置,就是设置开放哪个端口可用,自己去查

import os
import  socket
import json
import send
import time
class Data():
	def __init__(self,raspberryID,lasiodermaCount,lasiodermaID,currentTime,temperature,humidity,alarmSig1,alarmSig2,qrCode,remainingPower,warningImg):
		self.data_names = ['raspberryID','lasiodermaCount','lasiodermaID','currentTime','temperature','humidity',
					 'alarmSig1','alarmSig2','qrCode','remainingPower','warningImg']
		self.raspberryID = raspberryID
		self.lasiodermaCount = lasiodermaCount
		self.lasiodermaID = lasiodermaID
		self.CurrentTime = CurrentTime
		self.temperature = temperature
		self.humidity = humidity
		self.alarmSig1 = alarmSig1
		self.alarmSig2 = alarmSig2
		self.qrCode = qrCode
		self.remainingPower = remainingPower
		self.warningImg = warningImg

		self.data = [self.raspberryID,self.lasiodermaCount,self.lasiodermaID,
			   self.CurrentTime,self.temperature,self.humidity,self.alarmSig1,self.alarmSig2,self.qrCode,self.remainingPower,self.warningImg]
		
	def Json(self):
			
		data_dic = {key:value for key, value in zip(self.data_names,self.data)}
		return json.dumps(data_dic)
	
	def data_send(self):
		
		#Ip ='192.168.0.82'
		Ip = '127.0.0.1'
		Port= 8083
		
		
		data_json = self.Json()
		
		send.send_data(data_json,Ip,Port)
		
		return 'done'
		
		
if __name__=='__main__':
	raspberryID = 'No.1'
	lasiodermaCount = '5'
	lasiodermaID = str(['1','2','3'])
	CurrentTime = '2020/6/1 10:12:30'
	temperature = '28'
	humidity = '40.2%'
	alarmSig1 = '1'
	alarmSig2 = '1'
	qrCode = str([lasiodermaID,lasiodermaCount,CurrentTime])
	remainingPower = '20%'
	f = open('2.txt')
	warningImg = f.read()
	#AlarmImg = []
while 1:
		Data_send = Data(raspberryID,lasiodermaCount,lasiodermaID,CurrentTime,temperature,humidity,alarmSig1,alarmSig2,qrCode,remainingPower,warningImg)
		msg = Data_send.data_send()
		print(msg)
				
			
		
		
		
		
		
		

send.py  主函数调用

#!coding=utf-8
 
import os
import sys
import struct
import socket
import json
def send_data(data,Ip='192.168.0.82',Port=8083):

	try:
	    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	    
	    s.bind((Ip,Port))
	    print("successful")
	except socket.error as msg:
	    print (msg)
	    sys.exit(1)
	
	s.listen()
	
	conn,addr=s.accept()

	if data:

		data_new = bytes(data.encode('utf-8'))
		'''while 1:
			data_send = data_new.read(1024)
			if not data_send:
				print ('file send over...')
				break
			conn.send(data_send)'''
		conn.sendall(data_new)
	    # 关闭当期的套接字对象
		data = []
	s.close()

#repr()

2.在本地运行客户端程序 这里填写的ip地址是云服务器的公网地址,端口和云端设置的端口一样,这边设置的是每休眠10秒接受一次数据

 

# -*- coding: utf-8 -*-
"""
Created on Tue Jun  1 10:47:36 2021

@author: Jimmy_ouyang
"""


#模拟服务端

import os
import time
import  socket
sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

address=('127.0.0.1',8083)
sk.connect(address)
BASE_DIR=os.path.dirname(os.path.abspath(__file__))#获取绝对路径

print('waiting......')


while True:
	
	data=sk.recv(1024)


	if  data:
		print(data)
	else:    
		#print("receive over")

		time.sleep(10)
		continue


sk.close()

 

3.注意事项 要先开启云服务器上的服务端,开始循环监听以后 再开启本地的客户端,就实现了公网socket通信

你可能感兴趣的:(通信,socket,python,socket,网络)