Search code examples
pythonpython-3.xsocketsserver

How do I get my socket code to send more than one line


I am trying to create a socket server connection that sends manual input commands to the client.

I can send 1 command/line to it, but I am unable to get input() to prompt me for the second command and then send it. I can do it once, but not twice or more.

I tried giving it an if statement and another while loop. Neither produced the desired results.

import socket
import time

inputdata = input("Enter command: ")
test_data =  bytes(inputdata, encoding='utf-8')
s = socket.socket()
s.bind(('localhost', 667))
s.listen()
while True:
    c, addr = s.accept()
    if(test_data):
            c.send(test_data)
    time.sleep(.1)

If I put input() inside the loop, my code just hangs.

import socket
import time

inputdata = 0
#test_data =  bytes(inputdata)
s = socket.socket()
s.bind(('localhost', 667))
s.listen()
while True:
    c, addr = s.accept()
    inputdata = input("Enter command: ")
    test_data =  bytes(inputdata)
    if(test_data):
            c.send(test_data)
    time.sleep(.1)

How do I get my code to send more than 1 input() command/line to the client?


Solution

  • accept() shouldn't be in the loop, since it waits for another connection from the client.

    import socket
    import time
    
    inputdata = 0
    #test_data =  bytes(inputdata)
    s = socket.socket()
    s.bind(('localhost', 667))
    s.listen()
    c, addr = s.accept()
    while True:
        inputdata = input("Enter command: ")
        test_data =  bytes(inputdata)
        if(test_data):
            c.send(test_data)
        time.sleep(.1)