create a tcp client on a specific port in python

To create a TCP client, you can use the socket library in Python. Here is an example code that creates a TCP client on a specific port:

main.py
import socket

# Set up a TCP/IP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Define the IP address and port for the server to connect to
server_address = ('localhost', 8080)

# Connect to the server
client_socket.connect(server_address)

# Send data to the server
message = 'Hello, server!'
client_socket.sendall(message.encode())

# Receive data from the server
response = client_socket.recv(1024)
print(response.decode())

# Close the socket
client_socket.close()
498 chars
22 lines

In this example, we create a TCP/IP socket using the socket library. We then define the IP address and port for the server to connect to. After that, we use the connect() method to establish a connection to the server. We send data to the server using the sendall() method and receive data from the server using the recv() method. Finally, we close the socket using the close() method.

gistlibby LogSnag