前言
仙仙吐槽我的 ggntalk 不能保持连接,我发现好像在正常通讯过程中持续连接确实还是挺重要的(B/S架构好像就不那么重要),于是就写了一个持续链接版的 ggntalk2 。
ggntalk2.py
"""
ggntalk2 是 GGN_2015 在 ggntalk 的基础之上实现的新版通讯库
原先的 ggntalk 每次建立连接后只进行一次通信,现在 GGN_2015 打算让每次建立连接后能够建立多次通信
"""
VERSION = "2021-07-28"
import json
from threading import Thread
import socket
import traceback
config = {}
config_file = "config.json"
def get_config(filename = "config.json"):
"""
从 配置文件 中获取服务器配置信息
"""
new_config = {}
try:
with open(filename) as f:
new_config = json.load(f)
except:
print("config 文件不存在, 使用默认配置 ...")
new_config = {"ip":"127.0.0.1", "port":12345, "running": True, "maxlen": 1048576}
print(new_config)
return new_config
server = None
running = False
def keep_alive(connection_socket, addr):
"""
保持和客户端的持续连接
"""
while config["running"]:
print("服务器正在等待 " + str(addr) + "响应 ..")
message = connection_socket.recv(config["maxlen"]).decode("utf-8")
print("得到来自 " + str(addr) + " 的消息: " + message)
if message == "exit()":
print("接收到 exit 命令,服务器正在关闭")
connection_socket.send("服务器正在关闭".encode("utf-8"))
connection_socket.close()
try:
ans = eval(message)
except:
re_message = traceback.format_exc().encode("utf-8")
else:
re_message = json.dumps(ans).encode("utf-8")
finally:
connection_socket.send(re_message)
def server_run():
"""
在 server_start 执行后,运行服务器
"""
global config
global running
while config["running"]:
new_config = get_config(config_file)
if new_config != config:
config = new_config
running = False
break
print("服务器正在监听中 ip = %s port = %s ..." % (config["ip"], config["port"]))
try:
connection_socket, addr = server.accept()
except Exception as ex:
print(" 服务器 " + str(ex))
else:
print(" 得到来自 " + str(addr) + " 连接")
Thread(target=keep_alive, args=(connection_socket, addr)).start()
print("服务器运行结束 ip = %s port = %s ..." % (config["ip"], config["port"]))
def server_start():
"""
启动服务器 server
"""
if running:
print("服务器正在运行,无法再次启动服务器 ...")
else:
global server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, proto=6)
server.bind ((config["ip"], config["port"]))
server.listen(128)
server_run()
def debug_server():
"""
用于 ggntalk2 的测试主程序
"""
print("- 正在运行 ggntalk2 (VERSION = %s) 的测试程序 ..." % (VERSION))
server_start()
def client_fetch(client_socket, message = "print('hello world!')", max_recvlen = 1048576):
"""
向正在连接着的服务器发送请求
"""
client_socket.send(message.encode("utf-8"))
print("请求发送完毕,正在等待回复 ...")
re_message = client_socket.recv(max_recvlen).decode("utf-8")
return re_message
def client_connect(server_ip = "127.0.0.1", server_port = 12345):
"""
尝试与服务器进行连接,连接成功,返回接口类
"""
try:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((server_ip, server_port))
except:
print("连接失败 server_ip = %s, server_port = %d" % (server_ip, server_port))
return None
else:
print("连接成功!")
return client_socket
def client_test(client_socket):
try:
client_fetch(client_socket)
except:
return False
else:
return True
def client_close(client_socket):
"""
断开与服务器的连接
"""
return client_fetch(client_socket, "exit()")
if __name__ == "__main__":
config = get_config(config_file)
debug_server()
config.json
{
"ip": "127.0.0.1",
"port": 12345,
"maxlen": 1048576,
"running": true
}
|