Basic Python Socket Server Application Doesnt Result In Expected Output
Solution 1:
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:
whileTrue:
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.
Solution 2:
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 = 8686iflen(sys.argv) < 2elseint(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/receivesYou 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 = 8686iflen(sys.argv) < 2elseint(sys.argv[1])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # ipv4 versiontry:
s.bind((host, port))
s.listen(5)
print("listening TCP on {host} port {port}".format(**vars()))
whileTrue:
conn, addr = s.accept()
with closing(conn), closing(conn.makefile('rb')) as file:
for byte initer(lambda: file.read(1), b''):
# print numerical value of the byte as a decimal numberprint(ord(byte), end=' ')
print("") # received all input from the client, print a newlineexcept KeyboardInterrupt:
print('Keyboard interrupt received, exiting.')
finally:
s.close()
Post a Comment for "Basic Python Socket Server Application Doesnt Result In Expected Output"