Chris Aung
Chris Aung

Reputation: 9492

Python Simple Sever and Client script (Socket programming)

My objective is every time the client send the data to the server, the server will display it. But Currently when the client send the data, the server capture the data and display it only for the first time. What is causing the problem? Btw, this is my first time doing network programming, so pls keep your answer simple.

Server Script

import socket

server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.bine(("",5001))
server_socket.listen(5)

print "TCP Server Waiting for incoming client connection on port 5001..."

while True:
    client_socket, address =server_socket.accept()
    print "Connection from ", address
    data = client_socket.recv(512)
    print "RECIEVED:" , data

Client Script

import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('169.254.0.1', 5001))
data=''
while data!='quit':
        data = raw_input ( "SEND :" )
        client_socket.send(data)

Upvotes: 2

Views: 5760

Answers (2)

nouney
nouney

Reputation: 4411

while True:
    client_socket, address =server_socket.accept()
    print "Connection from ", address
    data = client_socket.recv(512)
    print "RECIEVED:" , data

This should be:

client_socket, address =server_socket.accept()
print "Connection from ", address
while True:
    data = client_socket.recv(512)
    print "RECIEVED:" , data

server_socket.accept() will wait indefinitely until a new client is connected. Actually your loop is like : "accept a client and receive one time the data he sent".

Upvotes: 1

falsetru
falsetru

Reputation: 368944

Your server code receive only once, then accept another client. You should loop until client disconnect. (when disconnected, recv() return empty string)

while True:
    client_socket, address = server_socket.accept()
    print "Connection from ", address
    while 1:
        data = client_socket.recv(512)
        if not data:
            break
        print "RECIEVED:" , data

BTW, your server code (and my code) does handle only one client at a time.

Upvotes: 2

Related Questions