我正在学习python中的套接字编程,
服务器代码:
import socket
srvsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srvsock.bind(('', 23000))
srvsock.listen(5)
while True:
clisock, (rem_host, rem_port) = srvsock.accept()
print "conection established with host %s and port %s" % (rem_host, rem_port)
while True:
strg = clisock.recv(20)
if not strg:
print 'conection closed'
clisock.close()
break
clisock.send(strg)
客户代码:
import socket
clisock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clisock.connect(('', 23000))
clisock.send("Hello World rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr dsadsadsa tttttt\n")
while True:
data = clisock.recv(20)
print type(data)
if not data:
clisock.close()
break
print data
我正在从客户端向服务器发送数据流,同时从服务器接收数据,在成功传输数据后,服务器未关闭客户端连接。我错过了什么吗?
答案 0 :(得分:1)
问题是由于服务器一直从客户端读取数据,直到它没有读取任何数据。这仅在连接的客户端关闭其连接时发生。在此之前,服务器套接字将阻止(即暂时中止操作),直到客户端发送更多数据。
底线:客户端或服务器必须表明它不再打算通过连接发送数据。
您可以通过添加行
来修复客户端clisock.shutdown(socket.SHUT_WR)
在客户端的for
循环之前。这表示不再发送数据。
答案 1 :(得分:0)
服务器代码:
while True:
clisock, (rem_host, rem_port) = srvsock.accept()
print "conection established with host %s and port %s" % (rem_host, rem_port)
while True:
strg = clisock.recv(20)
print '[message from client:] %s'%strg
clisock.send(strg)
print 'about to close with client'
clisock.close()
print 'connection closed with client'
break
客户代码:
clisock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clisock.connect(('', 23000))
clisock.send("Hello World rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr dsadsadsa tttttt\n")
while True:
data = clisock.recv(20)
print '[Message from server :]%s'%data
print 'about to close server connection'
clisock.close()
print 'server connection closed'
break
这将在你的情况下解决,holdenweb有正确的答案,为什么你的代码在上面的代码中表现不正常客户端只发送一条消息并关闭连接以及服务器只监听每个客户端的一条消息并关闭连接到该客户端单个客户端 - 单个连接----单个消息