Tag Archives: networking
C++ || Snippet – How To Send Text Over A Network Using A TCP Connection
The following is sample code which demonstrates the use of the “socket“, “connect“, “bind“, “read“, and “write” function calls for interprocess communication over a network on Unix based systems.
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. This program demonstrates communication between two programs using a TCP connection.
Click here to examine the UDP version.
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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
// ============================================================================ // Author: Kenneth Perkins // Date: Jan 8, 2014 // Taken From: http://programmingnotes.org/ // File: ServerTCP.cpp // 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, and 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. // ============================================================================ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> using namespace std; // Compile & Run // g++ ServerTCP.cpp -o ServerTCP // ./ServerTCP 1234 // the maximum size for sending/receiving text const int MSG_SIZE = 100; int main(int argc, char* argv[]) { // declare variables // the port number int port = -1; // the integer to store the file descriptor number // which will represent a socket on which the server // will be listening int listenfd = -1; // the file descriptor representing the connection to the client int connfd = -1; // the number of bytes read int numRead = -1; // the buffer to store text char data[MSG_SIZE]; // the structures representing the server and client // addresses respectively sockaddr_in serverAddr, cliAddr; // stores the size of the client's address socklen_t cliLen = sizeof(cliAddr); // make sure the user has provided the port number to listen on if(argc < 2) { cerr<<"\n** ERROR NOT ENOUGH ARGS!\n" <<"USAGE: "<<argv[0]<<" <SERVER PORT #>\n\n"; exit(1); } // get the port number port = atoi(argv[1]); // make sure that the port is within a valid range if(port < 0 || port > 65535) { cerr<<"Invalid port number\n"; exit(1); } // create a socket that uses // IPV4 addressing scheme (AF_INET), // Supports reliable data transfer (SOCK_STREAM), // and choose the default protocol that provides // reliable service (i.e. 0); usually TCP if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); exit(1); } // set the structure to all zeros memset(&serverAddr, 0, sizeof(serverAddr)); // convert the port number to network representation serverAddr.sin_port = htons(port); // set the server family serverAddr.sin_family = AF_INET; // retrieve packets without having to know your IP address, // and retrieve packets from all network interfaces if the // machine has multiple ones serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); // associate the address with the socket if(bind(listenfd, (sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) { perror("bind"); exit(1); } // listen for connections on socket listenfd. // allow no more than 100 pending clients. if(listen(listenfd, 100) < 0) { perror("listen"); exit(1); } cerr<<"\nServer started!\n"; // wait forever for connections to come while(true) { cerr<<"\nWaiting for someone to connect..\n"; // a structure to store the client address if((connfd = accept(listenfd, (sockaddr *)&cliAddr, &cliLen)) < 0) { perror("accept"); exit(1); } // receive whatever the client sends if((numRead = read(connfd, data, sizeof(data))) < 0) { perror("read"); exit(1); } // NULL terminate the received string data[numRead] = '\0'; cerr<<"\nRECEIVED: '"<<data<<"' from the client\n"; //cerr<<"Bytes read: "<<numRead<<endl; // set the array to all zeros memset(&data, 0, sizeof(data)); // retrieve the time time_t rawtime; time(&rawtime); struct tm* timeinfo; timeinfo = localtime(&rawtime); strftime(data, sizeof(data),"%a, %b %d %Y, %I:%M:%S %p", timeinfo); cerr<<"\nSENDING: '"<<data<<"' to the client\n"; // send the client a message if(write(connfd, data, strlen(data)+1) < 0) { perror("write"); exit(1); } // close the socket close(connfd); } return 0; }// 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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
// ============================================================================ // Author: Kenneth Perkins // Date: Jan 8, 2014 // Taken From: http://programmingnotes.org/ // File: ClientTCP.cpp // 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, and 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. // ============================================================================ #include <iostream> #include <cstdio> #include <ctime> #include <cstdlib> #include <cstring> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> using namespace std; // Compile & Run // g++ ClientTCP.cpp -o ClientTCP // ./ClientTCP 127.0.0.1 1234 // the maximum size for sending/receiving text const int MSG_SIZE = 100; int main(int argc, char* argv[]) { // declare variables // the port number int port = -1; // the file descriptor representing the connection to the client int connfd = -1; // the buffer to store text char data[MSG_SIZE] = "Server, what time is it?"; // the number of bytes read int numRead = -1; // the structures representing the server address sockaddr_in serverAddr; // stores the size of the client's address socklen_t servLen = sizeof(serverAddr); // make sure the user has provided the port number to listen on if(argc < 3) { cerr<<"\n** ERROR NOT ENOUGH ARGS!\n" <<"USAGE: "<<argv[0]<<" <SERVER IP> <SERVER PORT #>\n\n"; exit(1); } // get the port number port = atoi(argv[2]); // make sure that the port is within a valid range if(port < 0 || port > 65535) { cerr<<"Invalid port number\n"; exit(1); } // connect to the server if((connfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); exit(1); } // set the structure to all zeros memset(&serverAddr, 0, sizeof(serverAddr)); // set the server family serverAddr.sin_family = AF_INET; // convert the port number to network representation serverAddr.sin_port = htons(port); // convert the IP from the presentation format (i.e. string) // to the format in the serverAddr structure. if(!inet_pton(AF_INET, argv[1], &serverAddr.sin_addr)) { perror("inet_pton"); exit(1); } // connect to the server. This call will return a socket used // used for communications between the server and the client. if(connect(connfd, (sockaddr*)&serverAddr, sizeof(sockaddr)) < 0) { perror("connect"); exit(1); } cerr<<"\nSENDING: '"<<data<<"' to the server\n"; // send the server a message if(write(connfd, data, strlen(data)+1) < 0) { perror("write"); exit(1); } // receive whatever the server sends if((numRead = read(connfd, data, sizeof(data))) < 0) { perror("read"); exit(1); } // NULL terminate the received string data[numRead] = '\0'; cerr<<"\nRECEIVED: '"<<data<<"' from the server\n"; //cerr<<"Bytes read: "<<numRead<<endl; // close the connection socket close(connfd); return 0; }// 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, 07:51:53 PM" to the client
CLIENT OUTPUT:
SENDING: "Server, what time is it?" to the server
RECEIVED: "Wed, Jan 08 2014, 07:51:53 PM" from the server
C++ || Snippet – How To Send Text Over A Network Using A UDP Connection
The following is sample code which demonstrates the use of the “socket“, “bind“, “recvfrom“, and “sendto” function calls for interprocess communication over a network on Unix based systems.
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. This program demonstrates communication between two programs using a UDP connection.
Click here to examine the TCP version.
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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
// ============================================================================ // Author: K Perkins // Date: Jan 8, 2014 // Taken From: http://programmingnotes.org/ // File: ServerUDP.cpp // 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, and has the following functionality: // 1. Listen for incoming connections on a specified port. // 2. When a client connects, text is received from the client. // 3. Text is sent back to the client from the server. // 4. Go back to waiting for more connections. // ============================================================================ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <sys/socket.h> #include <netinet/in.h> using namespace std; // Compile & Run // g++ ServerUDP.cpp -o ServerUDP // ./ServerUDP 1234 // the maximum size for sending/receiving text const int MSG_SIZE = 100; int main(int argc, char* argv[]) { // declare variables // to store the port number int port = -1; // to store the socket file descriptor int socketfd = -1; // the address structures for the server and the client sockaddr_in servaddr, cliaddr; // the size of sockaddr_in structure socklen_t sockaddr_in_len = 0; // the number of bytes received and sent int numRead = -1, numSent = -1; // the buffer to store the string to send/receive char data[MSG_SIZE]; // check the command line if(argc < 2) { cerr<<"n** ERROR NOT ENOUGH ARGS!n" <<"USAGE: "<<argv[0]<<" <SERVER PORT #>n"; exit(1); } // convert the port number to an integer port = atoi(argv[1]); // make sure the port range is valid if(port < 0 || port > 65535) { cerr<<"nInvalid port numbern"; exit(1); } // create a UDP socket if((socketfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket"); exit(1); } // clear the structure for the server address memset(&servaddr, 0, sizeof(servaddr)); // populate the server address structure servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(port); // bind the socket to the port if(bind(socketfd,(sockaddr *)&servaddr, sizeof(servaddr)) < 0) { perror("bind"); exit(1); } cerr<<"nServer started!n"; // keep receiving forever while(true) { cerr<<"nWaiting for someone to connect..n"; // get the size of the client address data structure sockaddr_in_len = sizeof(cliaddr); // get something from the client; Will block until the client sends. if((numRead = recvfrom(socketfd, data, sizeof(data), 0, (sockaddr *)&cliaddr, &sockaddr_in_len)) < 0) { perror("recvfrom"); exit(1); } cerr<<"nRECEIVED: ""<<data<<"" from the clientn"; //cerr<<"Bytes read: "<<numRead<<endl; // set the array to all zeros memset(&data, 0, sizeof(data)); // retrieve the time time_t rawtime; time(&rawtime); struct tm* timeinfo; timeinfo = localtime(&rawtime); strftime(data, sizeof(data),"%a, %b %d %Y, %I:%M:%S %p", timeinfo); cerr<<"nSENDING: ""<<data<<"" to the clientn"; // send the time to the client if((numSent = sendto(socketfd, data, strlen(data)+1, 0, (sockaddr *)&cliaddr,sizeof(cliaddr))) < 0) { perror("sendto"); exit(1); } } return 0; }// 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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
// ============================================================================ // Author: K Perkins // Date: Jan 8, 2014 // Taken From: http://programmingnotes.org/ // File: ClientUDP.cpp // 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, and has the following functionality: // 1. Send text to the server on a specified port. // 2. Recieve text from the server and exit. // ============================================================================ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> using namespace std; // Compile & Run // g++ ClientUDP.cpp -o ClientUDP // ./ClientUDP 127.0.0.1 1234 // the maximum size for sending/receiving text const int MSG_SIZE = 100; int main(int argc, char* argv[]) { // declare variables // to store the port number int port = -1; // to store the socket file descriptor int socketfd = -1; // the address structures for the server and the client sockaddr_in servaddr, cliaddr; // the size of sockaddr_in structure socklen_t sockaddr_in_len = 0; // the number of bytes received and sent int numRead = -1, numSent = -1; // the buffer to store the string to send/receive char data[MSG_SIZE] = "Server, what time is it?"; // check the command line if(argc < 3) { cerr<<"n** ERROR NOT ENOUGH ARGS!n" <<"USAGE: "<<argv[0]<<" <SERVER IP> <SERVER PORT #>n"; exit(1); } // convert the port number to an integer port = atoi(argv[2]); // make sure the port range is valid if(port < 0 || port > 65535) { cerr<<"nInvalid port numbern"; exit(1); } // create a UDP socket if((socketfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket"); exit(1); } // clear the structure for the server address memset(&servaddr, 0, sizeof(servaddr)); // populate the server address structure servaddr.sin_family = AF_INET; // initialize the IP address of the server if(!inet_pton(AF_INET, argv[1], &servaddr.sin_addr.s_addr)) { perror("inet_pton"); exit(1); } // set the port servaddr.sin_port = htons(port); // get the size of the client address data structure sockaddr_in_len = sizeof(cliaddr); cerr<<"nSENDING: ""<<data<<"" to the servern"; // send the time to the client if((numSent = sendto(socketfd, data, strlen(data)+1, 0, (sockaddr *)&servaddr, sizeof(servaddr))) < 0) { perror("sendto"); exit(1); } // get something from the client; Will block until the client sends. if((numRead = recvfrom(socketfd, data, sizeof(data), 0, (sockaddr *)&cliaddr, &sockaddr_in_len)) < 0) { perror("recvfrom"); exit(1); } // NULL terminate the received string data[numRead] = ' '; cerr<<"nRECEIVED: ""<<data<<"" from the servern"; //cerr<<"Bytes read: "<<numRead<<endl; return 0; }// 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, 11:47:12 PM" to the client
CLIENT OUTPUT:
SENDING: "Server, what time is it?" to the server
RECEIVED: "Wed, Jan 08 2014, 11:47:12 PM" from the server
Java || Snippet – How To Send Text Over A Network Using Socket
The following is sample code which demonstrates the use of the “socket” function call 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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
// ============================================================================ // Author: K Perkins // Date: Jan 8, 2014 // Taken From: http://programmingnotes.org/ // File: Server.java // 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, and 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 java.io.*; import java.net.*; import java.util.Date; // Compile & Run // javac Server.java // java Server 1234 class Server { // the port on which to listen protected int listenPort; // the initialization constructor public Server(int port) { // save the listening port listenPort = port; }// end of Server // executes the main server loop public void mainServerLoop() throws Exception { // create a listening socket in the specified port. ServerSocket listenSock = new ServerSocket(this.listenPort); // keep servicing the clients while(true) { System.out.println("nWaiting for someone to connect.."); // accept the incoming connection from the client Socket communicationSocket = listenSock.accept(); // the client-to-server stream BufferedReader inFromClient = new BufferedReader(new InputStreamReader( communicationSocket.getInputStream())); // the server-to-client stream DataOutputStream outToClient = new DataOutputStream(communicationSocket.getOutputStream()); // display misc. IPC information System.out.println("n(SRCIP=" + communicationSocket.getInetAddress()+ ", SRCPORT="+communicationSocket.getPort() + ") "+"(DESTIP="+ communicationSocket.getLocalAddress()+", DESTPORT="+ communicationSocket.getLocalPort()+")"); // receive a string from the client String clientMsg = inFromClient.readLine(); System.out.println("nRECEIVED: ""+clientMsg+"" from the client"); // instantiate a date class: used for obtaining the current time Date date = new Date(); // send the current time and date to the client System.out.println("nSENDING: ""+date.toString()+"" to the client"); outToClient.writeBytes(date.toString()); // close the connection to the client communicationSocket.close(); } }// end of mainServerLoop public static void main(String[] args) { // make sure the port number is provided if(args.length != 1) { System.out.println("USAGE: java Server <SERVER PORT #>"); } else { // create an instance of the server class Server server = new Server(Integer.parseInt(args[0])); try { // start receiving client connections System.out.println("nServer started!"); server.mainServerLoop(); } catch(Exception e) { e.printStackTrace(); } } }// end of main }// 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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
// ============================================================================ // Author: K Perkins // Date: Jan 8, 2014 // Taken From: http://programmingnotes.org/ // File: Client.java // 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, and 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 java.io.*; import java.net.*; // Compile & Run // javac Client.java // java Client localhost 1234 class Client { // the server IP address protected String svrIpAddr; // the server port number protected int svrPort; /* the initialization constructor * @param ipAddr - the IP address of the server * @param port - the port on which the server is listening */ public Client(String ipAddr, int port) { // save the server's IP address and port number svrIpAddr = ipAddr; svrPort = port; }// end of Client // connects to the server public void connectToServer() throws Exception { // the message to send to the server String msgForServer = "Server, what time is it?"; // the string to store the date and time to be received from the server String dateAndTime = null; // create a socket and use it for connecting to the server Socket clientSocket = new Socket(svrIpAddr, svrPort); // the client-to-server stream DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); // the server-to-client stream BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // write the string to the server System.out.println("nSENDING: ""+msgForServer+"" to the servern"); outToServer.writeBytes(msgForServer+"n"); // get the date and time from the server dateAndTime = inFromServer.readLine(); // print the date and time received from the server System.out.println("RECEIVED: ""+dateAndTime+"" from the servern"); // close the socket clientSocket.close(); }// end of connectToServer public static void main(String args[]) { // check the command line arguments if(args.length < 2) { System.err.println("n** ERROR NOT ENOUGH ARGS!n" +"USAGE: Client <SERVER IP> <SERVER PORT #>n"); } else { // instantiate the client class Client client = new Client(args[0], Integer.parseInt(args[1])); try { // connect to the server client.connectToServer(); } catch(Exception e) { e.printStackTrace(); } } }// end of main }// 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..
(SRCIP=/127.0.0.1, SRCPORT=46608) (DESTIP=/127.0.0.1, DESTPORT=1234)
RECEIVED: "Server, what time is it?" from the client
SENDING: "Wed Jan 08 18:07:15 PST 2014" to the client
CLIENT OUTPUT:
SENDING: "Server, what time is it?" to the server
RECEIVED: "Wed Jan 08 18:07:15 PST 2014" from the server
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