Search code examples
pythonsocketserver

Socket Server//Not working


This is a socket server I created in Python, but when I run it, it highlight the while loop inside threaded_client and a alert box turn up. It says 'invalid syntax'. Can anyone tell me what is happening. Also, when I comment out anything, the error just moves onto the next line. Here is 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(5)
    print('Waiting...')
    def threaded_client(conn):
        conn.send(str.encode('TYPE HERE\n')

        while True:
            data = conn.recv(2048)
            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,)

Solution

  • You were missing parenthesis

    from thread import *
    import socket
    import sys
    
    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)
    print('Waiting...')
    
    def threadedClient(conn):
        conn.send(str.encode("Type Here\n"))
        while True:
          data = conn.recv(2048)
          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,))