1.功能介绍:
租用服务器,通过服务器作为信息传输中介,实现不同计算机之间的信息通信
2.为什么要租用服务器作为中间媒介?不可以直接进行两台设备之间的信息通信?
因为租用的服务器的IP地址是固定的,而个人设备(如手机、个人电脑)的IP地址随时在变化,如果将IP写入程序中,后期还需要更具IP变换修改程序,显然很不实用。
3.实现步骤
1.租用服务器,创建数据库
2.使用python连接数据库
3.通过登录相应账号,发送数据修改数据库,查询数据库获取接收的数据
import pymysql
import threading
import time
from tkinter import *
class MyThread1(threading.Thread):
def __init__(self, d):
super(MyThread1, self).__init__() # 重构run函数必须要写
self.userid = d[0]
self.cursor=d[1]
def run(self):
time_start = time.time()
ppid=-1
while (1):
time_end = time.time()
if time_end - time_start > 1:
time_start = time.time()
db = refreash()
self.cursor = db.cursor() # 获取光标
sql_select = "select receive from D where post=%s"
self.cursor.execute(sql_select, self.userid)
rett = self.cursor.fetchone()[0]
rece=rett.strip()
select_sql = "select * from D where post=%s"
self.cursor.execute(select_sql, rece)
receive = self.cursor.fetchone()
postid=int(receive[0])
data=receive[3]
if data != None and postid!=ppid:
dat = data.strip()
ppid=postid
print(rece + ":" + dat)
class MyThread2(threading.Thread):
def __init__(self, d):
super(MyThread2, self).__init__() # 重构run函数必须要写
self.userid = d[0]
self.cursor = d[1]
def run(self):
time_start = time.time()
while (1):
data = input("您输入的信息(输入0返回登录页):")
if data == '0':
menu(db)
sql_query = "update D set data=%s,ID=ID+1 where post=%s"
data = data.encode('GBK')
self.cursor.execute(sql_query, (data, self.userid))
db.commit()
def refreash():
db = pymssql.connect(
host='***.***.***.***',
port=3306,
user='root',
password='******',
database='soft',
charset='utf8'
) # 服务器名,账户,密码,数据库名
return db
def menu(db):
cursor = db.cursor() # 获取光标
userid=input("您的账号(输入exit退出系统):")
if userid=='exit':
exit()
password=input("您的密码:")
sql_select = "select password from U where userid=%s"
cursor.execute(sql_select, userid)
ps = cursor.fetchone()[0]
if password==ps:
print("登录成功!!!")
else:
print("登录失败!!!")
menu(db)
t1 = MyThread1((userid,cursor))
t2 = MyThread2((userid,cursor))
t1.start()
t2.start()
if __name__ == '__main__':
db = refreash()
menu(db)