我正在学习TCP,正在尝试一个客户端/服务器程序。我的服务器端正在工作,但是在客户端,我无法成功连接到服务器端。
客户端的错误代码
第一个错误:
回溯(最近通话最近): 在第13行的文件“ tcpclient.py”中 clientSocket.connect(((serverName,serverPort)) TypeError:应为str,字节或字节数组,而不是列表
第二个错误:
回溯(最近通话最近): 在第34行的文件“ tcpclient.py”中 clientSocket.send(clientSentence.encode(),serverAddress) TypeError:必须为整数(元组类型为元组)
服务器代码:此代码成功运行。
import sys
from socket import*
serverSocket = socket(AF_INET, SOCK_STREAM)
serversys = sys.argv
if len(serversys) == 1:
serverPort = 9999
else:
serverPort = serversys[1]
serverPort = int(serverPort)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print ("The server is ready to receive.")
while True:
connectionSocket, addr = serverSocket.accept()
print ("Connection accepted from: ", addr)
clientSentence = connectionSocket.recv(1024).decode()
clientSentence, clientAddress = serverSockset.recv(1024)
clientSentence.decode()
connectionSocket.close()
if clientSentence[0].decode() == 'U':
serverSentence = clientSentence.upper()
connectionSocket.send(serverSentence[1:].encode(), clientAddress)
connectionSocket.close()
elif clientSentence[0].decode() == 'L':
serverSentence = clientSentence.lower()
connectionSocket.send(serverSentence[1:].encode(), clientAddress)
connectionSocket.close()
elif clientSentence[0].decode() == 'I':
serverSentence = clientSentence.title()
connectionSocket.send(serverSentence[1:].encode(), clientAddress)
connectionSocket.close()
客户端:这是发生两个错误的地方。
import sys
from socket import*
clientSocket = socket(AF_INET, SOCK_STREAM)
clientsys = sys.argv
serverName = clientsys[1:]
serverPort = clientsys[2:]
clientSocket.connect((serverName, serverPort)) #First Error
serverPort = [int(serverPort) for serverPort in serverPort]
serverAddress = (serverName, serverPort)
sentenceChoice = input("Enter U for UPPERCASE SENTENCE, L for lowercase sentence, \nor I for Initial Caps Sentence: ")
sentence = input("Enter sentence: ")
clientSentence = sentenceChoice+sentence
clientSocket.send(clientSentence.encode(), serverAddress) #Second Error
serverSentence = clientSocket.recv(1024)
print('From Server: ', serverSentence.decode())
clientSocket.close()
答案 0 :(得分:1)
您确定它应该是clientsys [2:]而不是clientsys [2]吗?
答案 1 :(得分:1)
发生错误的原因是您正在使用列表切片从sys.argv
中查找服务器和端口:
clientsys[1:]
clientsys[2:]
列表切片操作的结果始终是列表:
l = [1, 2, 3]
>>>l[1:]
[2, 3]
>>>print(l[2:])
>>>[3]
相反,使用索引:
serverName = clientsys[0]
serverPort = clientsys[1]
答案 2 :(得分:1)
您的第一个错误是由您使用服务器名称和端口的列表片引起的。更改为此:
serverName = clientsys[1]
serverPort = clientsys[2]
您的第二个错误是因为socket.send()
不接受serverAddress
元组参数(您想到socket.sendto()
的地方吗?无论哪种方式,都可以通过删除参数来解决:>
clientSocket.send(clientSentence.encode())
链接到socket.send
文档:https://docs.python.org/3/library/socket.html#socket.socket.send