Blog

TCP Socket Programming in Python

Published 1 min read

Client

from socket import * serverName = "" serverPort = 12000 clientSocket = socket(AF_INET, SOCK_STREAM) # Set up a TCP connection between the client and the server. clientSocket.connect((serverName, serverPort)) sentence = input("Input lowercase sentence:") # Without attaching a destination address to the packet, # it simply hands the bytes of the sentence string to the TCP connection. clientSocket.send(sentence.encode()) # Characters from the server pile up in order. modifiedSentence = clientSocket.recv(1024) print("From Server: ", modifiedSentence.decode()) clientSocket.close()

Server

from socket import * serverPort = 80 serverSocket = socket(AF_INET, SOCK_STREAM) serverSocket.bind(("0", serverPort)) # Wait for and accept TCP connections (parameter: max number of queued connections) serverSocket.listen(1) print("The server is ready to receive") while True: # Create the connectionSocket socket. connectionSocket, addr = serverSocket.accept() sentence = connectionSocket.recv(1024).decode() capitalizedSentence = sentence.upper() connectionSocket.send(capitalizedSentence.encode()) connectionSocket.close()

Comments

Leaving a comment stores your nickname (or GitHub profile info). Privacy policy

GitHub