我目前正在编写我的第一个基本套接字服务器,我偶然发现了服务器与客户端通信的两种不同形式 - 线程(我认为conn
在 python 中使用)和channels
,我不太了解 - 但它们看起来像客户端和服务器之间通信的另一种方式。两者之间有什么区别以及如何最好地使用它们?
这是要求的代码-请原谅我的N00biness :)
连接/线程
def clientthread(conn):
#Sending message to connected client
#This only takes strings (words)
conn.send("Welcome to the server. Type something and hit enter\n")
#loop so that function does not terminate and the thread does not end
while True:
#Receiving from client
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
print data
#To close the connection
conn.close()
while True:
#Wait to accept a connection - blocking call
conn, addr = s.accept()
#display client information (IP address)
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#Start new thread takees 1st argument as a function name to be run, second
#is the tuple of arguments to the function
start_new_thread(clientthread ,(conn,))
频道
while True:
#Wait to accept a connection - blocking call
channel, details = s.accept()
#display client information (IP address)
print 'Connected with ', details
#Start new thread takees 1st argument as a function name to be run, second
#is the tuple of arguments to the function
#Sending message to connected client
#This only takes strings (words)
intro = "Welcome to the server. Type something and hit enter"
print channel.recv(len(intro))
channel.send(intro)
#loop so that function does not terminate and the thread does not end
while True:
#Receiving from client
data = channel.recv(1024)
if not data:
break
channel.sendall(data)
print data
channel
除了一种用途和另一种用途之外,它们做的事情完全相同conn
。