n12312
n12312

Reputation: 70

How can I receive more than one character at a time from telnet server?

I open up CMD and create a telnet connection with:

telnet localhost 5555

And the connection will open with the server printing "Welcome" as you can see in the image below

enter image description here

However, when I type on the telnet window it sends the reply one character at a time rather than in full sentences (e.g. I go to type hello and it sends hello world one character at a time), like this:

serveroutput: h serveroutput: e serveroutput: l serveroutput: l serveroutput: o

I want it to send the full word hello or a full sentence rather than sending one character at a time.

How can I do this?

Here's the code:

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(1)

def threaded_client(conn):
    conn.send(str.encode('Welcome, type your info\n'))

    while True:
        print("Waiting for input")
        data = conn.recv(1024)
        print("Data: ", data)
        reply = 'Server output: ' + data.decode('utf-8')   
        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,))

Thanks

Upvotes: 0

Views: 2287

Answers (1)

Selçuk Cihan
Selçuk Cihan

Reputation: 2034

As suggested in the comments, you need to code the logic for accumulating data. Something like:

line = ""
while True:
    data = conn.recv(1024)
    for c in data:
        if c == ord('\n'):
            print "message: " + line
            line = ""
        else:
            line = line + c
    if not data: 
        break

Upvotes: 1

Related Questions