Socket programming in Python - Transmission Control Protocol
Socket Programming TCP
Socket Programming for client-server communication using Transmission -Control-Protocol in Python.
TCP server:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | # Import socket library import socket # Create server serverPort = 1200 ServerName = 'localhost' ServerAddress = (ServerName, serverPort) # Create server socket serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Associate server port number with the socket serverSocket.bind(ServerAddress) # wait for some client to knock on the door serverSocket.listen(1) # maximum number of queued connections (atleast 1) print 'The server is ready to listen' while 1: # Create connection socket connection_socket, addr = serverSocket.accept() # Receive message from client message = connection_socket.recv(2048) # Modify the message modified_message = message.upper() # Send the modified message connection_socket.send(modified_message) print "Reply sent" print addr # Close communication with client connection_socket.close() |
TCP client:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | # Import libraries import socket # Create server ServerName = 'localhost' ServerPort = 1200 ServerAddress = (ServerName, ServerPort) # Create client socket clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # IPv4, TCP socket # Ask for connection to server clientSocket.connect(ServerAddress) # three-way handshake is performed # a TCP connection is established between the client and server. while 1: # Create message message = raw_input('Enter the lower case message: ') # Send message clientSocket.send(message) # Receive from server modified_sent = clientSocket.recvfrom(2048) # Print received message print "From server:", modified_sent continue # Close connection clientSocket.close() |
Comments
Post a Comment