Macintosh Fan
Macintosh Fan

Reputation: 405

Simple Python socket server does not run on macOS

I created a small Python socket server code, and when I try to connect with a client, I get:

OSError: [Errno 57] Socket is not connected

I'm not sure why I get that, even if the server is running.

Here is my code: server.py

# Imports
import socket


# Variables
ip_address = ''
ip_port = 10000
max_connections = 5

txt = 'utf-8'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


# Code
s.bind((socket.gethostname(), ip_port))
s.listen(max_connections)

while True:
    clientsocket, address = s.accept()
    print(f"{address} connected!")
    clientsocket.send(bytes("quit", txt))

client.py

# Imports
import socket


# Variables
ip_address = ''
ip_port = 10000

txt = 'utf-8'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
msg = s.recv(1024)


# Code
"""Connect to the server"""
s.connect((ip_address, ip_port))


while True:
    var = msg.decode(txt)
    print(var)
    if var == "quit":
        break

Upvotes: 0

Views: 1341

Answers (1)

Carlos Bazilio
Carlos Bazilio

Reputation: 960

I've changed some points in your code and it worked correctly here. I've setted ip_address to 127.0.0.1 worrying about security issues at MacOS. I also erased the second parameter of send function.

server.py

# Imports
import socket

# Variables
ip_address = '127.0.0.1'
ip_port = 10000
max_connections = 5

txt = 'utf-8'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Code
s.bind((ip_address, ip_port))
s.listen(max_connections)

while True:
    clientsocket, address = s.accept()
    print("{} connected!", address)
    clientsocket.send(b"quit")

At the client, recv was being called before socket connection.

client.py

# Imports
import socket

# Variables
ip_address = '127.0.0.1'
ip_port = 10000

txt = 'utf-8'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Code
"""Connect to the server"""
s.connect((ip_address, ip_port))

while True:
    msg = s.recv(1024)
    var = msg.decode(txt)
    if var == "quit":
        break

Upvotes: 1

Related Questions