0

Im trying to write a basic server / client application in python, where the clients sends the numbers 1-15 to the server, and the server prints it on the server side console.

Code for client:

import socket
clientsocket.connect(('localhost', 8303))
def updateX():
    x = 0
    while (x < 15):
        x
        clientsocket.send(format(x))
        print x
        x = x+1

updateX()

server:

import socket

HOST = 'localhost'
PORT = 8303
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5) # become a server socket, maximum 5 connections
connection, address = s.accept()

while True:
    connection, address = s.accept()
    buf = connection.recv(64)
    print buf

The output of running the client while the server is live results in either no output, prints only 1, or prints only 12. Ideas?

1
  • Where is your format()? Make sure you delimit your numbers from each other... Commented Apr 26, 2014 at 2:43

2 Answers 2

2

Before entering the main loop on the server side, you accept a connection:

connection, address = s.accept()

But then in the loop itself you begin by accepting a connection:

while True:
    connection, address = s.accept()
    buf = connection.recv(64)
    print buf

As a result, you never read from the first connection. That's why you don't see any output.

Note also that it's wrong (for what you're trying to do) to accept a new connection on every iteration. Even if you keep making new client connections, the server will accept a connection on each iteration and read from the socket once, but then continue the next iteration and wait for a new connection, never reading more data sent by a client. You should be making multiple recv calls on the same connection object instead.

You might find this tutorial helpful.

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

Comments

1

There are multiple errors:

  • socket.send() might send only partial content, use socket.sendall() instead
  • format(12) returns '12' therefore even if your code sends all numbers and the server correctly receives them then it sees '01234567891011121314' i.e., individual numbers are not separated
  • double socket.accept() mentioned by @Alp leads to ignoring the very first connection
  • socket.recv(64) may return less than 64 bytes, you need a loop until it returns an empty bytestring (meaning EOF) or use socket.makefile()

Client:

#!/usr/bin/env python
"""Send numbers in the range 0..14 inclusive as bytes e.g., 10 -> b'\n'

Usage: python client.py [port]
"""
import sys
import socket
from contextlib import closing

port = 8686 if len(sys.argv) < 2 else int(sys.argv[1])
with closing(socket.create_connection(('localhost', port))) as sock:
    sock.sendall(bytearray(range(15))) # send each number as a byte
    sock.shutdown(socket.SHUT_RDWR)    # no more sends/receives

You need to know how numbers are separated in the data. In this case, a fixed format is used: each number is a separate byte. It is limited to numbers that are less than 256.

And the corresponding server:

#!/usr/bin/env python
"""
Usage: python server.py [port]
"""
from __future__ import print_function
import sys
import socket
from contextlib import closing

host = 'localhost'
port = 8686 if len(sys.argv) < 2 else int(sys.argv[1])

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # ipv4 version
try:
    s.bind((host, port))
    s.listen(5)
    print("listening TCP on {host} port {port}".format(**vars()))
    while True:
        conn, addr = s.accept()
        with closing(conn), closing(conn.makefile('rb')) as file:
            for byte in iter(lambda: file.read(1), b''):
                # print numerical value of the byte as a decimal number
                print(ord(byte), end=' ')
            print("") # received all input from the client, print a newline
except KeyboardInterrupt:
    print('Keyboard interrupt received, exiting.')
finally:
    s.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.