对于我的simple socket server,我需要一个名为serverloop
(我试图提高我的函数技能)的函数。在此函数中,循环不断尝试连接潜在客户端:如何使用函数循环中定义的全局变量
def serverloop(s):
while True:
conn, addr = s.accept()
print "Connected with", addr
但是,conn
需要其他功能来运行:
def send_msg(conn):
#Send some data to the remote server
my_message = raw_input(">>>")
#set the whole string
conn.sendall(my_message)
我试图强迫康恩是全球性的与线global conn
,但我仍然收到错误:
NameError: global name 'conn' is not defined
注意:我必须使用线程。
我怎么能说尽管它是一个函数中定义的conn变量?
如何调用'send_msg'?从哪里来?它与“serverloop”有什么关系? –
**您在哪里添加了“global conn”这一行? –
@MartijnPieters我在不同的版本中添加了这个。为了复制这个问题,把'global conn'放在循环中,在accept线之上。 – xxmbabanexx