这是python中的套接字编程,其中python是服务器,而android是客户端。在这里,我从Android(客户端)接收QR码数据,该数据存储在df1对象中。另一个对象是MySQL数据库中的df2,其中包含与df1中相同的QR码数据。使用python,如何比较这两个对象的数据是否相同?
server-side.py
import socket
import sys
import pickle
def server_program():
HOST = '192.168.0.113' #this is your localhost
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#socket.socket: must use to create a socket.
#socket.AF_INET: Address Format, Internet = IP Addresses.
#socket.SOCK_STREAM: two-way, connection-based byte streams.
print('socket created')
#Bind socket to Host and Port
try:
s.bind((HOST, PORT))
except socket.error as err:
print('Bind Failed, Error Code: ' + str(err[0]) + ', Message: ' + err[1])
sys.exit()
print('Socket Bind Success!')
#listen(): This method sets up and start TCP listener.
s.listen(10)
print ('Socket is now listening')
while 1:
conn, addr = s.accept()
print ('Connect with ' + addr[0] + ':' + str(addr[1]))
df1 = conn.recv(1024).decode()
print(df1)
print('data recieved from client')
if not df1:
break
print("from connected user: " + str(df1))
df1 = input(' -> ')
conn.send(df1.encode())
break
conn.close()
s.close()
if __name__ == '__main__':
server_program()
我解决了这个问题,如下所示:
import mysql.connector as mysql # This module is used to connect python with MySQL database
import socket
import sys
import json
#import time
mydb1=mysql.connect(
user = 'rajat',
passwd = 'rajat',
host = 'localhost',
database = 'master_database'
)
# This is mysql database which is connected with python.
#Here we need user,host,password and database name to connect with python
# Its a mysql query which is selecting all fields from table where id is equals to one.
def server_program():
HOST = '192.168.0.116' #this is your localhost
PORT = 8007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#socket.socket: must use to create a socket.
#socket.AF_INET: Address Format, Internet = IP Addresses.
#socket.SOCK_STREAM: two-way, connection-based byte streams.
# Binding socket with post and host.
try:
s.bind((HOST, PORT))
except socket.error as err:
sys.exit()
#listen(): This method sets up and start TCP listener.
s.listen(2)
print ('Socket is now listening')
while True:
conn, addr = s.accept()#Accepting the connection and address of the client
df7 = conn.recv(1024)#Receiving the data in df7
df8 = json.loads(df7)
df2 = list(df8.values())#df7 is in dict format, so we convert it into list and take only values of that data.
mycursor1=mydb1.cursor()
mycursor1.execute("SELECT * FROM form_simpleform WHERE id=1")#Used for validating QR code data
df3=mycursor1.fetchone()
if df2 == (list(df3)): #If data is valid, it extracts the valid data of that id and send back the data to the client.
print('Data of QR Code also Exists')
else:
print("Data does not exists")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句