gpt4 book ai didi

python - 当我创建一个套接字时没有定义

转载 作者:行者123 更新时间:2023-12-03 11:52:46 25 4
gpt4 key购买 nike

我有一个程序,它只是通过 tkinter 接口(interface)向服务器发送消息。我正在使用各种子程序来运行基本的东西,比如开始一个新的连接和发送一条消息。唯一的问题是,当用户必须通过另一个子程序来建立连接时,它会不断出现名称错误“未定义客户端套接字”。

我尝试移动子程序,使 clientsocket 成为全局变量,并且我仔细检查了我的名字是否正确。我从函数中得到这些子程序的代码很好(我不久前在控制台中运行的一个聊天程序),所以它一定是我构建程序的方式。

这是所有处理套接字的子程序

def send_msg(): # Sends a message to the server (called from tkinter button)
try:
Csend = field.get("1.0", "end-1c")
Csend = str(Csend)
clientsocket.send(Csend.encode())

field.delete()
field.insert(END, "")
except error as err:
Csend = field.get("1.0", "end-1c") # 1.0 - Line one, char zero
print(f"Can't send message \"{Csend}\": Not connected to a server")
print(err)

def new_connection():
# Tkinter code goes here
def connect_server(): # Tries to connect to the server
try: # This runs the first check, if there is an existing connection
clientsocket.close()
except:
print("No existing connection")

try: # Runs the second check, if it can connect using the info
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = host_ent.get() # Gets STR of host IP
port = port_ent.get() # Gets STR of port
port = int(port) # Converts port to INT

clientsocket.connect((host, port)) # Connects to the server
except:
print("Could not connect, incorrect inputs?")

def disconnect_server():
try:
clientsocket.close()
except:
print("No existing connection")

所有这些子程序都是从 tkinter 菜单栏或按钮调用的。

我对套接字很陌生,所以如果任何代码是初学者级别的,那么我很抱歉。

提前感谢您的帮助!

最佳答案

问题是,您没有定义全局套接字,仅在函数中定义本地套接字。您应该添加 global clientsocket在您使用客户端套接字的每个函数的标题下。

关于python - 当我创建一个套接字时没有定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61156762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com