Python socket server only works sometimes

564 views Asked by At

I am new to python coding and tried to create a simple python socket server. I coded a client.py and a server.py on my laptop and it seems to work (It does what it is supposed to do....), but if i try to run the server on my laptop and the client on my other computer, it sometimes times out.

client.py

import socket

s = socket.socket()

host = '192.168.178.87'
port = 12345

s.connect((host, port))
print s.recv(1024)
s.sendall("greetings")

server.py

import socket

s = socket.socket()

host = ''
port = 12345
s.bind((host, port))

s.listen(5)

i = 0

while i < 5:
    c, addr = s.accept()
    print 'Got connection from', addr
    c.send('Thank you for connecting')
    data = c.recv(1024)
    print data
    c.close()
    i += 1
    print i
s.close()

I am using a FritzBox 7390, Both computers are in the same local network, both firewalls are turned off and no antivirus is installed.

I am using windows 7 and python 2.7 on both computers.

My problem summed up:

If I run the server on my laptop(192.168.178.87) and open the client.py via
cmd on the same computer , it works (I tried to use 127.0.0.1, 192.168.178.87 and my official ipv4 address(portforwarding in the router)) and everything works.

But if I try to use the client.py on my other computer (192.168.178.131) it
only works if I am the fifth to try to connect and I have no idea why.
I can connect to the server via browser, and it sometimes works, but mostly
there is an timeout error (Errno 10060).

What is the problem with my code?

0

There are 0 answers