hexce
hexce

Reputation: 161

Python server programming

I am trying a little client server project to get me into network programming but I seem to have got stuck at the first hurdle. I cant seem to get past getting the first line of data only even if its a new connection.

#!/usr/bin/python           

import socket               

s = socket.socket()         
host = '192.168.0.233'  # Test Server
port = 7777                
s.bind((host, port))        

s.listen(5)                 
while True:
    c, addr = s.accept()     
    print 'Got connection from', addr
    data = c.recv(2048)
    print(data)

If I telnet to the host running the server, the connection opens fine and I see on the server Got connection from addr, but I also only see the first line of data when I sent 4 lines of data,

I thought because its in a loop it should now always be looking for data?

I know im doing something wrong but unsure what.

Im using Python 2.6.6

Upvotes: 0

Views: 498

Answers (2)

nettux
nettux

Reputation: 5406

Try this:

#!/usr/bin/python

import socket
import threading

def listenForClients(sock):
    while True:
        client, address = sock.accept()
        client.settimeout(5)
        threading.Thread( target = listenToClient, args = (client,address) ).start()

def listenToClient(client, address):
    size = 2048
    while True:
        try:
            data = client.recv(size)
            if data:
                response = "Got connection"
                client.send(response)
            else:
                raise error('Client disconnected')
        except:
            client.close()
            return False

def main(host, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    sock.listen(5)
    listenForClients(sock)

if __name__ == "__main__":
    main('192.168.0.233',7777)

Here I use a thread for each client. The problem that you have with having Socket.accept() in the loop is that it blocks meaning that concurrent access won't work and you'll only be able to talk to one client at a time.

Try running it in the background and sending it messages with:

#!/usr/bin/python

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.0.233',7777))
vwhile True:
    data = raw_input("enter a message: ")
    sock.send(data)
    print sock.recv(2048)

Upvotes: 0

rpb
rpb

Reputation: 81

recv needs to be in a loop too, at the moment your code is receiving some data and then waiting for a new connection.

https://docs.python.org/2/library/socket.html#example has an example of socket.recv in a loop.

Upvotes: 1

Related Questions