python中socket通信

服务端
import socket
import sqlite3
import json
def stratDef(HOST,PORT,sqlconn,cursor):

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
while True:
try:
reply_map = dict()
conn, addr = s.accept()
print('Connected by ', addr)
data = conn.recv(1024).decode('unicode_escape')
print(data)
reply_map["call"] = "你好客户端,我是服务器"
reply_message = json.dumps(reply_map)
conn.send(reply_message.encode())
except Exception as e:
print(e.args)
if __name__ == "__main__":
HOST = "10.190.54.108"
PORT = 123
# 数据库连接 可以用sqlconn.commit()来结束当前sql语句关闭数据

sqlconn = sqlite3.connect("OMDatabase.db")
    # 用来执行语句

#cursor.execute("SELECT * from XXXTable where name = xxx and user = xxx", ("name","user",)) 执行语句
    #cursor_data = cursor.fetchall()    获得数据库返回信息

cursor = sqlconn.cursor()
cursor.execute("SELECT sql FROM sqlite_master WHERE type='table';")
print("strat connent server")
stratDef(HOST,PORT,sqlconn,cursor)

客户端

import socket
import sys
import json

def main():
# ip地址
HOST = '10.190.54.108'
# 端口号
PORT = 123

try:

s =socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
data_str = json.dumps("你好服务器,我是客户端")
s.send(data_str.encode())
data = s.recv(1024).decode()
data_map = json.loads(data)
print(data_map["call"])

pass
except Exception as e:
print(e.args)

if __name__ == "__main__":
main()


转载于:https://www.cnblogs.com/AEBOKE/p/11283392.html

你可能感兴趣的:(python中socket通信)