Search code examples
pythonpython-3.xtcp

Issues on error : fd, addr = self._accept()


Im trying to make a connection betwen server and client in python. but the program just running till waiting for a connection.The program cannot read the addres.

import socket
import sys

host = ''
port = 5131

s = socket.socket()

s.bind((host,port))

s.listen(1)
print('listening')


while 1:

    print('Waiting for a connection......')
    c, addr = s.accept()
    print('Connection established with', addr)


c.close()

and the result is like this :

listening
Waiting for a connection......
Traceback (most recent call last):
  File "/Users/muhrisdham/Downloads/tugas/01.tugas_tcp_server.py", line 32, in <module>
    c, addr = s.accept()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 212, in accept
    fd, addr = self._accept()
KeyboardInterrupt

pardon my english, thank you before


Solution

  • I assume you must have pressed ctrl+C when the program got stuck. Hence the KeyboardInterrupt.

    What you've written is the server. It's meant to block at the s.accept() call until a new connection is made to the address it's listening to (0.0.0.0:5131) in your case. Once a new connection is made you would handle that connection (somehow).

    Now all you've got left to do is to implement the client.

    Check out this tutorial: https://pymotw.com/2/socket/tcp.html