【问题标题】:Why does this not connect me to my server? [closed]为什么这不能将我连接到我的服务器? [关闭]
【发布时间】:2020-03-24 22:29:45
【问题描述】:

我正在尝试建立与 server.py 的连接,但 client.py 输出此错误

Traceback (most recent call last):
  File "C:\Users\Nathan\Desktop\Coding\Langs\Python\Projects\Chatting Program\Client.py", line 15, in <module>
    clientsocket.connect((host, port)) # Connects to the server
TypeError: an integer is required (got type str)

这是我的代码...

## CLIENT.PY
from socket import *
import socket

host = input("Host: ")
port = input("Port: ")
#int(port)

username = input("Username: ")
username = "<" + username + ">"
print(f"Connecting under nick \"{username}\"")

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creates socket
clientsocket.connect((host, port)) # Connects to the server

while True:
    Csend = input("<MSG> ") # Input message
    Csend = f"{username} {Csend}" # Add username to message
    clientsocket.send(Csend) # Send message to ONLY the server

如果我的 server.py 有问题,那么这里是代码

## SERVER.PY
from socket import *
import socket
import select

host_name = socket.gethostname()

HOST = socket.gethostbyname(host_name) 
PORT = 12345

print(f"Server Info\nHOST: {HOST}\nPORT: {PORT}")

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((HOST, PORT))
serversocket.listen(5)
clientsocket, address = serversocket.accept()

print(address)
with clientsocket:
    while True:
        Srecv = clientsocket.recv(1024)
        print(f"{username} - {address}: {Srecv}")
        # Add server time to message before sending
        clientsocket.sendall(Srecv)

我试过将host和port转换成str、int和float,但只能成功转换成str。任何帮助将不胜感激。提前致谢!

【问题讨论】:

  • 将端口号转换为整数是正确的方法。它有什么问题?
  • @mkrieger1 他没有设置参数的值。

标签: python python-3.x sockets python-sockets


【解决方案1】:

编译错误很公平:input() 返回一个字符串作为端口号,而您的函数需要一个整数。您可以通过将端口转换为整数来解决此问题 - 您的评论很接近:

端口 = int(端口)。

【讨论】:

    【解决方案2】:

    如果你查看 python 文档,input() 总是返回一个字符串。传递给 clientsocket.connect() 的元组中的第二个值必须是整数,但是,您传递的是字符串值。您必须先使用以下代码投射您的端口:

    port = int(port).
    
    #OR
    
    port = int(input("Port: "))
    

    始终检查文档!

    【讨论】:

    • 你的回答比我的添加了什么信息?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    相关资源
    最近更新 更多