1

I am trying to establish a connection to server.py but client.py outputs this error

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)

Here is my code...

## 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

If there is an issue with my server.py then here is the code to that

## 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)

I have tried converting host and port into str, int, and float, but it only successfully converts into str. Any help would be greatly appreciated. Thanks in advance!

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
NaNdy
  • 99
  • 8

2 Answers2

1

The compile error is pretty fair: input() returns a string for the port number, whereas your function needs an integer. You can fix that by casting the port to an integer - your comment is close:

port = int(port).

A. Abramov
  • 1,823
  • 17
  • 45
0

If you look at the python documentation, input() always returns a string. The second value in the tuple passed to clientsocket.connect() must be a integer, however, you are passing a your string value. You must cast your port first, with the following code:

port = int(port).

#OR

port = int(input("Port: "))

Always check the docs!

Isacc Barker
  • 507
  • 4
  • 15