代码100%可以运行,使用MongoDB数据库进行数据存储
import gevent
import pymongo
from gevent import monkey, socket
monkey.patch_all()
client = pymongo.MongoClient('192.168.8.10:27017') # 数据库地址
db = client['tcp_server'] # 数据库
collection = db['tcp_data'] # 数据表
def handle_request(cli, addr):
while True:
data = cli.recv(1024)
if not data:
cli.close()
break
print('client:', addr, 'recv:', data)
collection.insert_one({'client':addr, 'data':data.decode()})
cli.send('Roger that'.encode('UTF-8-SIG'))
def server(host, port):
s = socket.socket()
s.bind((host, port))
s.listen(5)
while True:
cli, addr = s.accept()
gevent.spawn(handle_request, cli, addr)
if __name__ == '__main__':
server('192.168.5.10', 8080) # 更改成运行这套代码的电脑ip
网友评论