在某些时候,我正在摆弄 Flask 套接字,但最终没有使用这些库,然后我恢复了我的代码,但最终出现了套接字错误,即使我的代码不再包含与双向套接字连接远程相关的任何内容。
以下是我的代码(抱歉,我的代码仍然很糟糕):
import time, json, xxhash, threading, random
from flask import Flask, request
from string import digits
from random import choice
app = Flask(__name__)
target = 5
last_block, key = time.time(), int(''.join(choice(digits) for i in range(8)))
pending_transactions, pending_data = [], []
user_data = {}
def import_user_data(username):
with open(f'user_data\\{username}.json', 'r') as f:
return json.load(f)
def export_user_data(username, data):
with open(f'user_data\\{username}.json', 'w') as f:
return json.dump(data, f)
def create_user_data(user, password):
try:
with open(f'user_data\\{user}.json', 'x') as f:
json.dump({"password": password, "balance": 0, "transactions": []}, f)
return True
except Exception:
return False
def get_balance(user):
data = import_user_data(user)
return data.get("balance")
def post_transaction(amount, sender, recipient, memo):
txid = xxhash.xxh64(random.randbytes(64)).hexdigest()
if sender != "Mainnet":
user = import_user_data(sender)
if len(user["transactions"]) >= 25:
user["transactions"].pop(-1)
user["transactions"].append({"txid": txid, "sender": sender, "recipient": recipient, "amount": amount, "memo": memo})
export_user_data(sender, user)
user = import_user_data(recipient)
if len(user["transactions"]) >= 25:
user["transactions"].pop(-1)
user["transactions"].append({"txid": txid, "sender": sender, "recipient": recipient, "amount": amount, "memo": memo})
export_user_data(recipient, user)
return txid
def payout(username):
global target
data = import_user_data(username)
reward = target * 10 + 1
data["balance"] += reward
export_user_data(username, data)
post_transaction(reward, "Mainnet", username, f"mining reward! (target: {target})")
def transfer(sender, recipient, amount):
data = import_user_data(sender)
if not float(data.get("balance")) < float(amount):
data["balance"] -= float(amount)
export_user_data(data, sender)
data = import_user_data(recipient)
data["balance"] += float(amount)
export_user_data(data, recipient)
return {"txid": post_transaction(amount, sender, recipient, memo)}
def new_block(block, last_block):
global target, key
t = block - last_block
key = int(''.join(choice(digits) for i in range(8)))
if t > 80:
target -= 1
if t < 50:
target += 1
for i in range(0, len(pending_transactions)):
pass
def chain():
global target, last_block
try:
while True:
if time.time() - last_block > 81:
target -= 1
last_block = time.time()
time.sleep(30)
except Exception as e:
print(e)
@app.route("/create_account")
def create_acc():
try:
e, t = time.time(), target
if request.json["hash"] == xxhash.xxh64(request.json["nonce"], seed=int(e)).hexdigest():
username, password = xxhash.xxh64(random.randbytes(64)).hexdigest(), xxhash.xxh64(random.randbytes(64)).hexdigest()
create_user_data(username, password)
return {"output": True, "username": username, "password": password}
except Exception as e:
return {"output": False, "info": e}
@app.route("/mine", methods=['GET', 'POST'])
def mine():
global key, last_block, target
if request.method == "GET":
return {"target": target, "key": key}
else:
e, t = time.time(), target
if request.json["hash"] == xxhash.xxh64(request.json["nonce"], seed=key).hexdigest():
new_block(e, last_block)
last_block = e
payout(request.json["username"])
return {"output": True, "info": "you have submitted a valid block!"}
else:
return {"output": False, "info": "your submission is invalid"}
if __name__ == '__main__':
c = threading.Thread(target=chain)
c.start()
app.run(debug=True, port=80, host="127.0.0.1")
如果需要提供更多信息,请告诉我
编辑:以下是错误以及回溯:
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\threading.py", line 980, in _bootstrap_inner
self.run()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\threading.py", line 917, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\jerrb\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\werkzeug\serving.py", line 804, in serve_forever
super().serve_forever(poll_interval=poll_interval)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\socketserver.py", line 232, in serve_forever
ready = selector.select(poll_interval)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\selectors.py", line 324, in select
r, w, _ = self._select(self._readers, self._writers, [], timeout)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\selectors.py", line 315, in _select
r, w, x = select.select(r, w, w, timeout)
OSError: [WinError 10038] An operation was attempted on something that is not a socket
经过几个小时的忙碌和浏览互联网,ChatGPT 设法在 3 分钟内解决了我的问题。我通过使用以下 cmd 命令完全重新安装 Winsock2 解决了我的问题。
netsh winsock reset catalog
netsh int ipv4 reset reset.log
netsh int ipv6 reset reset.log
该问题是由 Winsock2 严重损坏引起的
其他解决方案对我不起作用。这是一个对我有用的解决方案:
import select
_ORIGINAL_SELECT = select.select
def _safe_select(*args, **kwargs):
try:
return _ORIGINAL_SELECT(*args, **kwargs)
except OSError as e:
if e.errno == 10038:
return [], [], []
else:
raise
select.select = _safe_select
此代码可防止
select.select()
引发 OSError 10038