freedome97 freedome97 - 2 months ago 15
Python Question

Python 3 Sockets - Receiving more then 1 character

So when I open up the CMD and create a telnet connection with:

telnet localhost 5555

It will apear a "Welcome", as you can see on the screen below.
After that every single character I type into the CMD will be printed out/send immediately.
My Question is: Is it, and if yes, how is it possible to type in messages and then send them so I receive them as 1 sentence and not char by char.
enter image description here

import socket
import sys
from _thread import *

host = ""
port = 5555
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

try:
s.bind((host,port))
except socket.error as e:
print(str(e))

s.listen(5) #Enable a server to accept connections.
print("Waiting for a connection...")

def threaded_client(conn):
conn.send(str.encode("Welcome\n"))

while True:
# for m in range (0,20): #Disconnects after x chars
data = conn.recv(2048) #Receive data from the socket.
reply = "Server output: "+ data.decode("utf-8")
print(data)
if not data:
break
conn.sendall(str.encode(reply))
conn.close()

while True:
conn, addr = s.accept()
print("connected to: "+addr[0]+":"+str(addr[1]))
start_new_thread(threaded_client,(conn,))

Answer

You need to keep reading until the stream ends:

string = ""

while True:
# for m in range (0,20): #Disconnects after x chars
    data = conn.recv(1) #Receive data from the socket.

    if not data:
        reply = "Server output: "+ string
        conn.sendall(str.encode(reply))
        break
    else:
        string += data.decode("utf-8")

conn.close()

By the way, using that method you'll read one char at a time. You may adapt it to the way your server is sending the data.

Comments