Doe J
Doe J

Reputation: 13

How can I create a TCP server using Python 3?

How can I create a TCP server in python3 which will return all the files in the current directory?

Upvotes: 1

Views: 6397

Answers (2)

user6244313
user6244313

Reputation:

You can use socketserver which will serve the current working directory.

import socketserver  # import socketserver preinstalled module
import http.server
httpd = socketserver.TCPServer(("127.0.0.1", 9000), http.server.SimpleHTTPRequestHandler)
httpd.serve_forever()

Upvotes: 1

Christian Clarke
Christian Clarke

Reputation: 61

You can use the socketserver library, this will serve the current working directory. Here is the Server code

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The request handler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())
        # here you can do self.request.sendall(use the os library and display the ls command)

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
        # Activate the server; this will keep running until you
        # interrupt the program with Ctrl-C
        server.serve_forever()

And here is the client side

import socket
import sys

HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])

# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(bytes(data + "\n", "utf-8"))

    # Receive data from the server and shut down
    received = str(sock.recv(1024), "utf-8")

print("Sent:     {}".format(data))
print("Received: {}".format(received))

You should then get an output like

Server:

127.0.0.1 wrote:
b'hello world with TCP'
127.0.0.1 wrote:
b'python is nice'

Client:

$ python TCPClient.py hello world with TCP
Sent:     hello world with TCP
Received: HELLO WORLD WITH TCP
$ python TCPClient.py python is nice
Sent:     python is nice
Received: PYTHON IS NICE

You can then just use this code to send the current directory list

Upvotes: 3

Related Questions