我正在使用TCP connecton SOCK_STREAM编写python服务器客户端。
我能够从客户端建立一个连接,服务器返回响应。
我第二次失去连接
这是服务器代码
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort = 62175
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print('The server is ready to receive information')
connectionSocket, addr = serverSocket.accept()
while True:
sentence = connectionSocket.recv(1024).decode()
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence.encode())
connectionSocket.close()
这是客户端的代码
from socket import *
import sys
import re
serverName = 'localhost'
serverPort = 62175
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
done = False
while done == False:
sentence = input("Input a lowercase sentence: ")
try:
inputValue = int(sentence)
print("Input data is an integer, suppose to be a string, Run the program again")
except ValueError:
try:
if(regex.search(sentence) == None):
if (sentence.lower() == "quit"):
done = True
clientSocket.close()
elif (sentence == ""):
print("There wasn't any input detected. Try again")
else:
clientSocket.sendall(sentence.encode())
modifiedSentence = clientSocket.recv(1024)
print(modifiedSentence.decode())
print(done)
else:
print("String contains special characters, Try again")
except OSError as err:
print("OS error: {0}".format(err))
这是我输入第二个输入时的输出和错误
Input a lowercase sentence: test
TEST
False
Input a lowercase sentence: test
OS error: [WinError 10053] An established connection was aborted by the software in your host machine
谢谢您的协助
您的服务器在循环内关闭了连接,但尝试通过关闭的套接字进行通信:
connectionSocket, addr = serverSocket.accept()
while True:
sentence = connectionSocket.recv(1024).decode()
...
connectionSocket.close()
要处理多个连接recv
并send
在连接内,您应该close
仅在实际完成时调用:
connectionSocket, addr = serverSocket.accept()
while True:
sentence = connectionSocket.recv(1024).decode()
...
connectionSocket.close()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句