0

I've tried to connect two computers with a socket in Python and I don't know why it doesn't work. The files are from internet and it compiles for me but without any results.

The server.py:

#!/usr/bin/python import socket s = socket.socket() host = '' port = 12345 s.bind((host, port)) s.listen(5) while True: c, addr = s.accept() print 'Got connection from', addr c.send('Thank you for connecting') c.close() 

and the client.py:

#!/usr/bin/python import socket s = socket.socket() host = # here I put the ip of the server's laptop port = 12345 s.connect((host, port)) print s.recv(1024) s.close() 

What's wrong?

9
  • This won't work, because there's a syntax error in the code. Anyhow, where is that code from? I'm asking because it is for old Python 2, and probably outdated. Commented Oct 13, 2015 at 19:36
  • tutorialspoint.com/python/python_networking.htm it's from here. Commented Oct 13, 2015 at 19:40
  • What results are you expecting? BTW, you can try replacing send with sendall. Commented Oct 13, 2015 at 19:47
  • After fixing indentations and using localhost, this code worked for me. Are you saying nothing printed? You should have gotten an error exception at the least. Commented Oct 13, 2015 at 19:49
  • 1
    I know that the issues are miniscule, @tdelaney, but it still suggests that the tutorial is outdated. If you look around a bit, you will find lots of ads, a 10$ download for the PDF and all that for a tutorial obviously based on Python 2.4. This is a tutorial to avoid! Instead, use docs.python.org/3/library/socket.html and a contemporary Python version. Commented Oct 13, 2015 at 20:13

1 Answer 1

1

You have to run the server first. Then run the client at the same time with the IP of the server (I used localhost because it was running on one computer, maybe you should try if that works). The code worked fine for me, every time I ran the client, the server printed a message. If it doesn't work for you, maybe your firewall is not letting you open ports.

Just for the future, please always post any error messages you see.

BTW, isn't this the Python Documentation example for sockets?

Sign up to request clarification or add additional context in comments.

2 Comments

I think this better written as a comment than an answer. OP hasn't told us what went on. And it is very close to the simple examples in the doc.
I fixed all the indentation problems. I used the IP of the server (I am running on two computers) and is still not receveing any message.. But still, I'm not sure what did you mean by "run the client at the same time with the IP of the server", how's that, if I run the server first?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.