Python || Snippet – How To Send Text Over A Network Using Socket, Send, & Recv
The following is sample code which demonstrates the use of the “socket“, “connect“, “send“, and “recv” function calls for interprocess communication over a network.
The following example demonstrates a simple network application in which a client sends text to a server, and the server replies (sends text) back to the client.
Note: The server program must be ran before the client program!
=== 1. 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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# ============================================================================= # Author: Kenneth Perkins # Date: Jan 8, 2014 # Taken From: http://programmingnotes.org/ # File: Server.py # Description: This program implements a simple network application in # which a client sends text to a server and the server replies back to the # client. This is the server program, which has the following functionality: # 1. Listen for incoming connections on a specified port. # 2. When a client tries to connect, the connection is accepted. # 3. When a connection is created, text is received from the client. # 4. Text is sent back to the client from the server. # 5. Close the connection and go back to waiting for more connections. # ============================================================================= import socket, sys, datetime # Run # python3 Server.py 1234 # the client message size MAX_MSG_LEN = 4096 def main(argc, argv): # check the command line arguments if(argc < 2): print("\n** ERROR NOT ENOUGH ARGS!\n" "USAGE: %s <SERVER PORT #>\n" %(argv[0])) sys.exit(1) # get the port number port = int(argv[1]) # the backlog backlog = 100 # create A TCP socket listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # bind the socket to the port listenSocket.bind(("", port)) # start listening for incoming connections listenSocket.listen(backlog) print("\nServer started!") # service clients forever while(True): print("\nWaiting for someone to connect..") # accept a connection from the client client, address = listenSocket.accept() # get the data from the client data = client.recv(MAX_MSG_LEN) print("\nRECEIVED: '%s' from the client" %(data.decode("UTF-8"))) # make sure the data was successfully received if(data): # get the current date and time now = datetime.datetime.now() dateAndTime = now.strftime("%a, %b %d %Y, %I:%M:%S %p") # send the date and time to the client print("\nSENDING: '%s' to the client" %(dateAndTime)) client.send(dateAndTime.encode("UTF-8")) # close the connection to the client client.close() if __name__ == "__main__": main(len(sys.argv), sys.argv) # http://programmingnotes.org/ |
=== 2. 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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# ============================================================================= # Author: Kenneth Perkins # Date: Jan 8, 2014 # Taken From: http://programmingnotes.org/ # File: Client.py # Description: This program implements a simple network application in # which a client sends text to a server and the server replies back to the # client. This is the client program, which has the following functionality: # 1. Establish a connection to the server. # 2. Send text to the server. # 3. Recieve text from the server. # 4. Close the connection and exit. # ============================================================================= import socket, sys # Run # python3 Client.py localhost 1234 # the size of the message sent by server MAX_MSG_LEN = 4096 def main(argc, argv): # check the command line arguments if(argc < 3): print("\n** ERROR NOT ENOUGH ARGS!\n" "USAGE: %s <SERVER IP> <SERVER PORT #>\n" %(argv[0])) sys.exit(1) # get the host name (or IP) host = argv[1] # get the server's port number port = int(argv[2]) # the client socket clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # connect to the server clientSocket.connect((host,port)) # send a string to the server data = "Server, what time is it?" print("\nSENDING: '%s' to the server" %(data)) clientSocket.send(data.encode("UTF-8")) # get the date from the server data = clientSocket.recv(MAX_MSG_LEN) print("\nRECEIVED: '%s' from the server\n" %(data.decode("UTF-8"))) # close the connection to the server clientSocket.close() if __name__ == "__main__": main(len(sys.argv), sys.argv) # http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
The following is sample output.
SERVER OUTPUT:
Server started!
Waiting for someone to connect..
RECEIVED: "Server, what time is it?" from the client
SENDING: "Wed, Jan 08 2014, 04:02:13 PM" to the client
CLIENT OUTPUT:
SENDING: "Server, what time is it?" to the server
RECEIVED: "Wed, Jan 08 2014, 04:02:13 PM" from the server
Leave a Reply