You are on page 1of 52

Shri Shankaracharya Technical Campus

Shri Shankaracharya Technical Campus


Bhilai

NETWORK PROGRAMMING
LAB
BE CSE 7th Semester

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 1


Shri Shankaracharya Technical Campus

List of experiment to be performed

Unix

1. Write an echo program with client and iterative server using TCP. [By Teacher]

2. Write an echo program with client and iterative server using UDP. [By Teacher]

3. Write a program to retrieve date and time using TCP. [By Teacher]

4. Write a program to retrieve date and time using UDP. [By Teacher]

5. Write a client program that gets a number from the user and sends the number to server for
conversion in to hexadecimal and gets the result from the server in TCP. [Assignment to Student]

6. Write a client program that gets a number from the user and sends the number to server for
conversion in to hexadecimal and gets the result from the server in UDP. [Assignment to Student]

Java
7. Write an echo program with client and iterative server using TCP. [By Teacher]

8. Write an echo program with client and iterative server using UDP. [Assignment to Student]

9. Write an echo program with client and concurrent server using TCP. [By Teacher]

10. Write an echo program with client and concurrent server using UDP. [Assignment to Student]

11. Write a client server program for chatting. [By Teacher].

12. Write a client and server program to implement file transfer. [By Teacher]

13. Write a client and server program to implement the remote command execution. [By Teacher]

14. Write a client program that gets a number from the user and sends the number to server for
converting it into words gets the result from the server in TCP. (for example if we enter 86 then
server will return Eighty Six)[Assignment to Student]

15. Write a Client Server Program to exchange keys and generate shared secret key using diffi-
hellmen algorithm.

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 2


Shri Shankaracharya Technical Campus

Experiment No. 01
Write an echo program with client and iterative server using TCP.

Server

Algorithm:-
Step1: Start the program.
Step2: Create server socket.
Step3: Listen on specified port.
Step4: Wait for client connection.
Step5: Accept connection.
Step6: Send the message to the client.
Step7: Close client connection.
Step 8: Close server socket.
Step 9: Stop the program.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main()
{
int sock, connected, bytes_recieved , true =1;
char send_data [1024]={"Hello User!!"}, recv_data[1024];

struct sockaddr_in server_addr,client_addr;


int sin_size;

if((sock = socket(AF_INET, SOCK_STREAM,0))==-1){


perror("Socket");
exit(1);
}

if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int))==-1){
perror("Setsockopt");
exit(1);
}

server_addr.sin_family = AF_INET;
Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 3
Shri Shankaracharya Technical Campus

server_addr.sin_port = htons(5000);
server_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(server_addr.sin_zero),8);

if(bind(sock,(struct sockaddr *)&server_addr,sizeof(struct sockaddr))==-1){


perror("Unable to bind");
exit(1);
}

if(listen(sock,5)==-1){
perror("Listen");
exit(1);
}

printf("\nTCPServer Waiting for client on port 5000");


fflush(stdout);
sin_size =sizeof(struct sockaddr_in);
connected = accept(sock,(struct sockaddr *)&client_addr,&sin_size);
printf("\n I got a connection from (%s , %d)\n",
inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
send(connected, send_data,strlen(send_data),0);
close(connected);
close(sock);
return0;
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 4


Shri Shankaracharya Technical Campus

Client:

Algorithm:-
Step1: Start the program.
Step2: Create socket.
Step3: connect to server.
Step4: get data from server.
Step5: Close socket.
Step 6: Stop the program.

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int main()

int sock, bytes_recieved;


char send_data[1024],recv_data[1024];
struct hostent *host;
struct sockaddr_in server_addr;

host = gethostbyname("127.0.0.1");

if((sock = socket(AF_INET, SOCK_STREAM,0))==-1){


perror("Socket");
exit(1);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr =*((struct in_addr *)host->h_addr);
bzero(&(server_addr.sin_zero),8);

if(connect(sock,(struct sockaddr *)&server_addr,


sizeof(struct sockaddr))==-1)
{
perror("Connect");

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 5


Shri Shankaracharya Technical Campus

exit(1);
}

bytes_recieved=recv(sock,recv_data,1024,0);
recv_data[bytes_recieved]='\0';
printf("\nRecieved data = %s\n ", recv_data);
//send(sock,send_data,strlen(send_data), 0);
close(sock);
return0;
}

Output:

1. Server:

a@a-ThinkCentre-A58:~/SS$ gcc tcpserver1.c


a@a-ThinkCentre-A58:~/SS$ ./a.out

TCPServer Waiting for client on port 5000


I got a connection from (127.0.0.1 , 47144)
a@a-ThinkCentre-A58:~/SS$

2. Client:
a@a-ThinkCentre-A58:~/SS$ gcc tcpserver1.c
a@a-ThinkCentre-A58:~/SS$ ./a.out

TCPServer Waiting for client on port 5000


I got a connection from (127.0.0.1 , 47144)
a@a-ThinkCentre-A58:~/SS$

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 6


Shri Shankaracharya Technical Campus

Experiment No. 02
Write an echo program with client and iterative server using UDP.

Server

Algorithm:-

Step1: Start the program.


Step2: Create server socket.
Step3: Get the message from client.
Step4: Stop the program.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main()
{
int sock;
int addr_len, bytes_read;
char recv_data[1024];
struct sockaddr_in server_addr , client_addr;

if((sock = socket(AF_INET, SOCK_DGRAM,0))==-1){


perror("Socket");
exit(1);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(server_addr.sin_zero),8);

if(bind(sock,(struct sockaddr *)&server_addr,


sizeof(struct sockaddr))==-1)
{
perror("Bind");
exit(1);
}
Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 7
Shri Shankaracharya Technical Campus

addr_len =sizeof(struct sockaddr);

printf("\nUDPServer Waiting for client on port 5000");


fflush(stdout);
bytes_read = recvfrom(sock,recv_data,1024,0,
(struct sockaddr *)&client_addr,&addr_len);

recv_data[bytes_read]='\0';

printf("\n(%s , %d) said : ",inet_ntoa(client_addr.sin_addr),


ntohs(client_addr.sin_port));
printf("%s\n", recv_data);
fflush(stdout);

return0;
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 8


Shri Shankaracharya Technical Campus

Client:

Algorithm:-
Step1: Start the program.
Step2: Create socket.
Step 3: get data from server.
Step 4: Stop the program.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main()
{
int sock;
struct sockaddr_in server_addr;
struct hostent *host;
char send_data[1024];

host=(struct hostent *) gethostbyname((char*)"127.0.0.1");

if((sock = socket(AF_INET, SOCK_DGRAM,0))==-1)


{
perror("socket");
exit(1);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr =*((struct in_addr *)host->h_addr);
bzero(&(server_addr.sin_zero),8);

printf("Type Something :");


gets(send_data);
sendto(sock, send_data, strlen(send_data),0,
(struct sockaddr *)&server_addr,sizeof(struct sockaddr));

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 9


Shri Shankaracharya Technical Campus

Output
Server

a@a-ThinkCentre-A58:~/SS$ gcc udpserver.c


a@a-ThinkCentre-A58:~/SS$ ./a.out

UDPServer Waiting for client on port 5000


(127.0.0.1 , 33196) said : Hello
a@a-ThinkCentre-A58:~/SS$

Client

a@a-ThinkCentre-A58:~/SS$ gcc udpclient.c


/tmp/ccGsrg97.o: In function `main':
udpclient.c:(.text+0xca): warning: the `gets' function is dangerous and should not be used.
a@a-ThinkCentre-A58:~/SS$ ./a.out
Type Something :Hello
a@a-ThinkCentre-A58:~/SS$

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 10


Shri Shankaracharya Technical Campus

Experiment No. 03
Write a program to retrieve date and time using TCP

Server

Algorithm:-
Step 1: Start the program.
Step 2: Create server socket.
Step 3: Listen on specified port.
Step 4: Wait for client connection.
Step 5: Accept connection.
Step 6: Send the date to the client.
Step 7: Close client connection.
Step 8: Close server socket.
Step 9: Stop the program.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <time.h>

int main()
{
int sock, connected, bytes_recieved , true =1;
char send_data [1024]={"Hello User!!"}, recv_data[1024];

struct sockaddr_in server_addr,client_addr;


int sin_size;

if((sock = socket(AF_INET, SOCK_STREAM,0))==-1){


perror("Socket");
exit(1);
}

if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int))==-1){
perror("Setsockopt");
exit(1);
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 11


Shri Shankaracharya Technical Campus

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(server_addr.sin_zero),8);

if(bind(sock,(struct sockaddr *)&server_addr,sizeof(struct sockaddr))


==-1){
perror("Unable to bind");
exit(1);
}

if(listen(sock,5)==-1){
perror("Listen");
exit(1);
}

printf("\nTCPServer Waiting for client on port 5000\n");


fflush(stdout);
sin_size =sizeof(struct sockaddr_in);
connected = accept(sock,(struct sockaddr *)&client_addr,&sin_size);
printf("\n I got a connection from (%s , %d)\n",
inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
/*getting current time*/
time_t current_time;
char* c_time_string;
/* Convert to local time format. */
c_time_string = ctime(&current_time);
/* Print to stdout. */
(void) printf("Current time is %s", c_time_string);

send(connected, c_time_string,strlen(c_time_string),0);
close(connected);
close(sock);
return0;
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 12


Shri Shankaracharya Technical Campus

Client:

Algorithm:-
Step 1: Start the program.
Step 2: Create socket.
Step 3: connect to server.
Step 4: get date from server.
Step 5: Close socket.
Step 6: Stop the program.
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int main()

int sock, bytes_recieved;


char recv_data[1024];
struct hostent *host;
struct sockaddr_in server_addr;

host = gethostbyname("127.0.0.1");

if((sock = socket(AF_INET, SOCK_STREAM,0))==-1){


perror("Socket");
exit(1);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr =*((struct in_addr *)host->h_addr);
bzero(&(server_addr.sin_zero),8);

if(connect(sock,(struct sockaddr *)&server_addr,


sizeof(struct sockaddr))==-1)
{
perror("Connect");
exit(1);
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 13


Shri Shankaracharya Technical Campus

bytes_recieved=recv(sock,recv_data,1024,0);
recv_data[bytes_recieved]='\0';
printf("\nRecieved data = %s ", recv_data);
close(sock);
return0;
}

Output
1. Server
a@a-ThinkCentre-A58:~/SS$ gcc tcpdateserver.c
a@a-ThinkCentre-A58:~/SS$ ./a.out

TCPServer Waiting for client on port 5000

I got a connection from (127.0.0.1 , 47145)


Current time is Thu Jan 1 05:30:00 1970
a@a-ThinkCentre-A58:~/SS$

2. Client

a@a-ThinkCentre-A58:~/SS$ gcc tcpdateclient.c


a@a-ThinkCentre-A58:~/SS$ ./a.out

Recieved data = Thu Jan 1 05:30:00 1970


a@a-ThinkCentre-A58:~/SS$

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 14


Shri Shankaracharya Technical Campus

Experiment No. 04
Write a program to retrieve date and time using UDP

Serve

Algorithm:-

Step1: Start the program.


Step2: Create server socket.
Step3: Get the message from client.
Step4: Send date to client.
Step5: Stop the program.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main()
{
int sock;
int addr_len, bytes_read;
char recv_data[1024];
char send_data[1024]="Hello";
struct sockaddr_in server_addr , client_addr;

if((sock = socket(AF_INET, SOCK_DGRAM,0))==-1){


perror("Socket");
exit(1);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(server_addr.sin_zero),8);

if(bind(sock,(struct sockaddr *)&server_addr,


sizeof(struct sockaddr))==-1)
{

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 15


Shri Shankaracharya Technical Campus

perror("Bind");
exit(1);
}

addr_len =sizeof(struct sockaddr);

printf("\nUDPServer Waiting for client on port 5000\n");


fflush(stdout);
bytes_read = recvfrom(sock,recv_data,1024,0,
(struct sockaddr *)&client_addr,&addr_len);

recv_data[bytes_read]='\0';

printf("\n(%s , %d) said : ",inet_ntoa(client_addr.sin_addr),


ntohs(client_addr.sin_port));
printf("%s\n", recv_data);
fflush(stdout);
/*getting current time*/
time_t current_time;
char* c_time_string;
/* Convert to local time format. */
c_time_string = ctime(&current_time);
/* Print to stdout. */
(void) printf("Current time is %s", c_time_string);
sendto(sock, c_time_string, strlen(c_time_string),0,
(struct sockaddr *)&client_addr,sizeof(struct sockaddr));

return0;
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 16


Shri Shankaracharya Technical Campus

Client:

Algorithm:-
Step 1: Start the program.
Step 2: Create socket.
Step 3: send data to server.
Step 4: get date from server.
Step 5: Stop the program.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main()
{
int sock;
struct sockaddr_in server_addr;
struct hostent *host;
char send_data[1024]={"Please send me current date and time"};
char recv_data[1024];
int addr_len, bytes_read;

host=(struct hostent *) gethostbyname((char*)"127.0.0.1");

if((sock = socket(AF_INET, SOCK_DGRAM,0))==-1)


{
perror("socket");
exit(1);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr =*((struct in_addr *)host->h_addr);
bzero(&(server_addr.sin_zero),8);

sendto(sock, send_data, strlen(send_data),0,


(struct sockaddr *)&server_addr,sizeof(struct sockaddr));

addr_len =sizeof(struct sockaddr);


Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 17
Shri Shankaracharya Technical Campus

fflush(stdout);
bytes_read = recvfrom(sock,recv_data,1024,0,
(struct sockaddr *)&server_addr,&addr_len);

recv_data[bytes_read]='\0';

printf("\n(%s , %d) said : ",inet_ntoa(server_addr.sin_addr),


ntohs(server_addr.sin_port));
printf("%s\n", recv_data);
fflush(stdout);

Output
Server
a@a-ThinkCentre-A58:~/SS$ gcc udpdatentimeserver.c
udpdatentimeserver.c: In function ‘main’:
udpdatentimeserver.c:57: warning: assignment makes pointer from integer without a cast
a@a-ThinkCentre-A58:~/SS$ ./a.out

UDPServer Waiting for client on port 5000

(127.0.0.1 , 47806) said : Please send me current date and time


Current time is Thu Jan 1 05:30:00 1970
a@a-ThinkCentre-A58:~/SS$

Client
a@a-ThinkCentre-A58:~/SS$ gcc udpdatentimeclient.c
a@a-ThinkCentre-A58:~/SS$ ./a.out

(127.0.0.1 , 5000) said : Thu Jan 1 05:30:00 1970

a@a-ThinkCentre-A58:~/SS$

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 18


Shri Shankaracharya Technical Campus

Experiment No. 05
Write a client program that gets a number from the user and sends the number to server for conversion in
to hexadecimal and gets the result from the server in TCP.

Server

Algorithm:-
Step1: Start the program.
Step2: Create server socket.
Step3: Listen on specified port.
Step4: Wait for client connection.
Step5: Accept connection.
Step6: Get a integer from client.
Step7: Send the hexadecimal of received integer to the client.
Step8: Close client connection.
Step 9: Close server socket.
Step 10: Stop the program.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>

int main()
{
int sock, connected, bytes_recieved , true =1;
char send_data [1024], recv_data[1024];

struct sockaddr_in server_addr,client_addr;


int sin_size;

if((sock = socket(AF_INET, SOCK_STREAM,0))==-1){


perror("Socket");
exit(1);
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 19


Shri Shankaracharya Technical Campus

if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int))==-1){
perror("Setsockopt");
exit(1);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(server_addr.sin_zero),8);

if(bind(sock,(struct sockaddr *)&server_addr,sizeof(struct sockaddr))


==-1){
perror("Unable to bind");
exit(1);
}

if(listen(sock,5)==-1){
perror("Listen");
exit(1);
}

printf("\nTCPServer Waiting for client on port 5000\n");


fflush(stdout);
sin_size =sizeof(struct sockaddr_in);
connected = accept(sock,(struct sockaddr *)&client_addr,&sin_size);
printf("\n I got a connection from (%s , %d)\n",
inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
bytes_recieved=recv(connected,recv_data,1024,0);
recv_data[bytes_recieved]='\0';
printf("\nRecieved data = %s \n", recv_data);
int n = atoi(recv_data);
sprintf(send_data,"%x", n);
printf("received %s to int %d Converted to hex %s\n",recv_data,n,send_data);

send(connected, send_data,strlen(send_data),0);
close(connected);
close(sock);
return0;
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 20


Shri Shankaracharya Technical Campus

Client:

Algorithm:-
Step 1: Start the program.
Step 2: Create socket.
Step 3: connect to server.
Step 4: Send an integer to server.
Step 4: Get Hexadecimal value of corresponding integer from server.
Step 5: Close socket.
Step 6: Stop the program.

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>

int main()

int sock, bytes_recieved;


int number=10;
char send_data[1024],recv_data[1024];
struct hostent *host;
struct sockaddr_in server_addr;

host = gethostbyname("127.0.0.1");

if((sock = socket(AF_INET, SOCK_STREAM,0))==-1){


perror("Socket");
exit(1);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr =*((struct in_addr *)host->h_addr);
bzero(&(server_addr.sin_zero),8);

if(connect(sock,(struct sockaddr *)&server_addr,


sizeof(struct sockaddr))==-1)

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 21


Shri Shankaracharya Technical Campus

{
perror("Connect");
exit(1);
}
printf("Sending %d to conver to hex\n ",number);
//itoa(number, send_data, 10);
sprintf(send_data,"%d", number);
send(sock, send_data,strlen(send_data),0);
bytes_recieved=recv(sock,recv_data,1024,0);
recv_data[bytes_recieved]='\0';
printf("\nRecieved data = %s\n ", recv_data);
close(sock);
return0;
}

Output
Server

a@a-ThinkCentre-A58:~/SS$ gcc tcphexserver.c


a@a-ThinkCentre-A58:~/SS$ ./a.out

TCPServer Waiting for client on port 5000

I got a connection from (127.0.0.1 , 46006)

Recieved data = 10
received 10 to int 10 Converted to hex a
a@a-ThinkCentre-A58:~/SS$

Client
a@a-ThinkCentre-A58:~/SS$ gcc tcphexclient.c
a@a-ThinkCentre-A58:~/SS$ ./a.out
Sending 10 to conver to hex

Recieved data = a
a@a-ThinkCentre-A58:~/SS$

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 22


Shri Shankaracharya Technical Campus

Experiment No. 06
Write a client program that gets a number from the user and sends the number to server for conversion in
to hexadecimal and gets the result from the server in UDP.

Server

Algorithm:-
Step1: Start the program.
Step2: Create server socket.
Step3: Get the integer from client.
Step4: Send the hexadecimal value of corresponding integer.
Step5: Stop the program.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main()
{
int sock;
int addr_len, bytes_read;
char recv_data[1024];
char send_data[1024]="Hello";
struct sockaddr_in server_addr , client_addr;

if((sock = socket(AF_INET, SOCK_DGRAM,0))==-1){


perror("Socket");
exit(1);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(server_addr.sin_zero),8);

if(bind(sock,(struct sockaddr *)&server_addr,


sizeof(struct sockaddr))==-1)

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 23


Shri Shankaracharya Technical Campus

{
perror("Bind");
exit(1);
}

addr_len =sizeof(struct sockaddr);

printf("\nUDPServer Waiting for client on port 5000\n");


fflush(stdout);
bytes_read = recvfrom(sock,recv_data,1024,0,
(struct sockaddr *)&client_addr,&addr_len);

recv_data[bytes_read]='\0';

printf("\n(%s , %d) : ",inet_ntoa(client_addr.sin_addr),


ntohs(client_addr.sin_port));
printf("%s sent \n", recv_data);
fflush(stdout);
int n = atoi(recv_data);
sprintf(send_data,"%x", n);

(void) printf("number in hex %s\n", send_data);


sendto(sock, send_data, strlen(send_data),0,
(struct sockaddr *)&client_addr,sizeof(struct sockaddr));

return0;
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 24


Shri Shankaracharya Technical Campus

Client

Algorithm:-
Step 1: Start the program.
Step 2: Create socket.
Step 3: send integer value to server.
Step 4: get corresponding hexadecimal value from server.
Step 5: Stop the program.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main()
{
int sock;
struct sockaddr_in server_addr;
struct hostent *host;
char send_data[1024]={"Please send me current date and time"};
int number;
char recv_data[1024];
int addr_len, bytes_read;

host=(struct hostent *) gethostbyname((char*)"127.0.0.1");

if((sock = socket(AF_INET, SOCK_DGRAM,0))==-1)


{
perror("socket");
exit(1);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr =*((struct in_addr *)host->h_addr);
bzero(&(server_addr.sin_zero),8);

printf("Enter a number");
scanf("%d",&number);
sprintf(send_data,"%d", number);

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 25


Shri Shankaracharya Technical Campus

sendto(sock, send_data, strlen(send_data),0,


(struct sockaddr *)&server_addr,sizeof(struct sockaddr));

addr_len =sizeof(struct sockaddr);

fflush(stdout);
bytes_read = recvfrom(sock,recv_data,1024,0,
(struct sockaddr *)&server_addr,&addr_len);

recv_data[bytes_read]='\0';

printf("\n(%s , %d) said : ",inet_ntoa(server_addr.sin_addr),


ntohs(server_addr.sin_port));
printf("%s\n", recv_data);
fflush(stdout);

Output
Server
a@a-ThinkCentre-A58:~/SS$ gcc udphexserver.c
a@a-ThinkCentre-A58:~/SS$ ./a.out

UDPServer Waiting for client on port 5000

(127.0.0.1 , 48072) : 12 sent


number in hex c
a@a-ThinkCentre-A58:~/SS$

Client
a@a-ThinkCentre-A58:~/SS$ gcc udphexserver.c
a@a-ThinkCentre-A58:~/SS$ ./a.out

UDPServer Waiting for client on port 5000

(127.0.0.1 , 48072) : 12 sent


number in hex c
a@a-ThinkCentre-A58:~/SS$

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 26


Shri Shankaracharya Technical Campus

Experiment No. 07
Write an echo program with client and iterative server using TCP.

Server

Algorithm:-

Step1: Start the program.


Step2: Create server socket.
Step3: accept client Connection.
Step4: Get Message from server.
Step3: Send message to client.
Step4: Close the connection.
Step5: Stop the program.

import java.net.*;
import java.io.*;

publicclass TcpEchoServer {

privatestatic Socket socket;

publicstaticvoid main(String[] args){


try{

int port =25002;


ServerSocket serverSocket =new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr =new InputStreamReader(is);
BufferedReader br =new BufferedReader(isr);
String name = br.readLine();
System.out.println("Message received from client is "+ name);
//processesing data
String returnMessage ="Hello "+ name +" !!\n";
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw =new OutputStreamWriter(os);
BufferedWriter bw =new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+ returnMessage);
bw.flush();

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 27


Shri Shankaracharya Technical Campus

}catch(Exception e){
e.printStackTrace();
}finally{
try{
socket.close();
}catch(Exception e){
}
}
}
}

Client

Algorithm:-
Step 1: Start the program.
Step 2: Create socket.
Step 3: Send message to server.
Step 4: Get message from server.
Step 5: Close socket.
Step 6: Stop the program.

import java.net.*;
publicclass TcpEchoClient {

privatestatic Socket socket;

publicstaticvoid main(String args[]){


try{
String host ="localhost";
int port =25002;
InetAddress address = InetAddress.getByName(host);
socket =new Socket(address, port);

//Send the message to the server


OutputStream os = socket.getOutputStream();
OutputStreamWriter osw =new OutputStreamWriter(os);
BufferedWriter bw =new BufferedWriter(osw);

String Name ="John";

String sendMessage = Name +"\n";


bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+ sendMessage);

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 28


Shri Shankaracharya Technical Campus

//Get the return message from the server


InputStream is = socket.getInputStream();
InputStreamReader isr =new InputStreamReader(is);
BufferedReader br =new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : "+ message);
}catch(Exception exception){
exception.printStackTrace();
}finally{
//Closing the socket
try{
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}

Output

Server
Server Started and listening to the port 25000
Message received from client is John
Message sent to the client is Hello John !!

Client
Message sent to the server : John

Message received from the server : Hello John !!

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 29


Shri Shankaracharya Technical Campus

Experiment No. 08
Write an echo program with client and iterative server using UDP.

Server

Algorithm:-
Step1: Start the program.
Step2: Create server socket.
Step4: Get Message from server.
Step3: Send message to client.
Step4: Close the connection.
Step5: Stop the program.

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

publicclass UDPEchoServer {

publicstaticvoid main(String args[])throws Exception {

//Creating Datagram Server Socket


DatagramSocket serverSocket =new DatagramSocket(9876);
byte[] receiveData =newbyte[1024];
byte[] sendData =newbyte[1024];
//receive data from client
System.out.println("Waiting for client");
DatagramPacket receivePacket =new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence =new String(receivePacket.getData());
System.out.println("Received from client: "+ sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
//sending data to client
System.out.println("Sending to client: "+ capitalizedSentence);
DatagramPacket sendPacket =new DatagramPacket(sendData, sendData.length, IPAddress,
port);
serverSocket.send(sendPacket);
}
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 30


Shri Shankaracharya Technical Campus

Client

Algorithm:-
Step 1: Start the program.
Step 2: Create socket.
Step 3: Send message to server.
Step 4: Get message from server.
Step 5: Close socket.
Step 6: Stop the program.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

publicclass UDPEchoClient1 {
publicstaticvoid main(String args[])throws Exception {
System.out.println("Write some content to send to server\n");
BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));
//creates a DatagramSocket:
DatagramSocket clientSocket =new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");

byte[] sendData =newbyte[1024];


byte[] receiveData =newbyte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
//sending data to server:
DatagramPacket sendPacket =new DatagramPacket(sendData, sendData.length,
IPAddress,9876);
clientSocket.send(sendPacket);
//receiving data from server
DatagramPacket receivePacket =new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence =new String(receivePacket.getData());
System.out.println("Received data from server :"+ modifiedSentence);
clientSocket.close();
}
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 31


Shri Shankaracharya Technical Campus

Output
Server
Waiting for client
Received from client: Hello
Client
Write some content to send to server

Hello

Received data from server :HELLO

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 32


Shri Shankaracharya Technical Campus

Experiment No. 09
Write an echo program with client and concurrent server using TCP

Server

Algorithm:-
Step1: Start the program.
Step2: Create server socket.
Step3: accept client Connection.
Step4: Get an integer value from client.
Step3: Send square of received integer value to client.
Step4: Close the connection.
Step5: Stop the program.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

publicclass TCPConcurrentServer {

privatestatic Socket socket;

publicstaticvoid main(String[] args){


try{

int port =25001;


ServerSocket serverSocket =new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");

//Server is running always. This is done using this while(true) loop


while(true){
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr =new InputStreamReader(is);
BufferedReader br =new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+ number);

//Multiplying the number by 2 and forming the return message


Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 33
Shri Shankaracharya Technical Campus

String returnMessage;
try{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat *2;
returnMessage = String.valueOf(returnValue)+"\n";
}catch(NumberFormatException e){
//Input was not a number. Sending proper message back to client.
returnMessage ="Please send a proper number\n";
}

//Sending the response back to the client.


OutputStream os = socket.getOutputStream();
OutputStreamWriter osw =new OutputStreamWriter(os);
BufferedWriter bw =new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+ returnMessage);
bw.flush();
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
socket.close();
}catch(Exception e){
}
}
}
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 34


Shri Shankaracharya Technical Campus

Client

Algorithm:-
Step 1: Start the program.
Step 2: Create socket.
Step 3: Send an integer value to server.
Step 4: Get square of sent integer from server.
Step 5: Close socket.
Step 6: Stop the program.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

publicclass TCPEchoClient1 {

privatestatic Socket socket;

publicstaticvoid main(String args[]){


try{
String host ="localhost";
int port =25001;
InetAddress address = InetAddress.getByName(host);
socket =new Socket(address, port);

//Send the message to the server


OutputStream os = socket.getOutputStream();
OutputStreamWriter osw =new OutputStreamWriter(os);
BufferedWriter bw =new BufferedWriter(osw);

String number ="2";

String sendMessage = number +"\n";


bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+ sendMessage);

//Get the return message from the server


InputStream is = socket.getInputStream();
InputStreamReader isr =new InputStreamReader(is);
BufferedReader br =new BufferedReader(isr);
String message = br.readLine();

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 35


Shri Shankaracharya Technical Campus

System.out.println("Message received from the server : "+ message);


}catch(Exception exception){
exception.printStackTrace();
}finally{
//Closing the socket
try{
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}

Output

Server
Server Started and listening to the port 25000
Message received from client is 2
Message sent to the client is 4
Client
Message sent to the server : 2

Message received from the server : 4

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 36


Shri Shankaracharya Technical Campus

Experiment No.10
Write an echo program with client and concurrent server using UDP.

Server

Algorithm:-
Step1: Start the program.
Step2: Create server socket.
Step4: Get Message from server.
Step3: Send message to client.
Step4: Close the connection.
Step5: Stop the program.

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

publicclass UDPConcurrentServer {

publicstaticvoid main(String args[])throws Exception {

//Creating Datagram Server Socket


DatagramSocket serverSocket =new DatagramSocket(9877);
byte[] receiveData =newbyte[1024];
byte[] sendData =newbyte[1024];
while(true){
System.out.println("Waiting for client");
//receive data from client
DatagramPacket receivePacket =new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence =new String(receivePacket.getData());
System.out.println("Received data from client : "+ sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
//sending data to client
System.out.println("Sending data to client : "+ capitalizedSentence);
DatagramPacket sendPacket =new DatagramPacket(sendData, sendData.length,
IPAddress, port);
serverSocket.send(sendPacket);
}
}
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 37


Shri Shankaracharya Technical Campus

Client

Algorithm:-
Step 1: Start the program.
Step 2: Create socket.
Step 3: Send message to server.
Step 4: Get message from server.
Step 5: Close socket.
Step 6: Stop the program.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

publicclass UDPEchoClient1 {
publicstaticvoid main(String args[])throws Exception {
System.out.println("Write some content to send to server\n");
BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));
//creates a DatagramSocket:
DatagramSocket clientSocket =new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");

byte[] sendData =newbyte[1024];


byte[] receiveData =newbyte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
//sending data to server:
DatagramPacket sendPacket =new DatagramPacket(sendData, sendData.length,
IPAddress,9877);
clientSocket.send(sendPacket);
//receiving data from server
DatagramPacket receivePacket =new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence =new String(receivePacket.getData());
System.out.println("Received data from server :"+ modifiedSentence);
clientSocket.close();
}
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 38


Shri Shankaracharya Technical Campus

Output
Server
Waiting for client
Received data from client : Hello Friends
Client
Write some content to send to server

Hello Friends

Received data from server :HELLO FRIENDS

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 39


Shri Shankaracharya Technical Campus

Experiment No.12
Write a client and server program to implement file transfer.

Server

Algorithm:-
Step1: Start the program.
Step2: Create server socket.
Step3: accept client Connection.
Step 4: Send file to client.
Step5: Close the connection.
Step6: Stop the program.

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

publicclass TCPFileTransferServer {

publicstaticvoid main(String[] args)throws IOException {


ServerSocket servsock =new ServerSocket(1234);
File myFile =new File("E://kv.oxps");
while(true){
System.out.println("Waiting for client");
Socket sock = servsock.accept();
byte[] mybytearray =newbyte[(int) myFile.length()];
BufferedInputStream bis =new BufferedInputStream(new FileInputStream(myFile));
bis.read(mybytearray,0, mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending file data to client");
os.write(mybytearray,0, mybytearray.length);
System.out.println("Sent file successfully to client");
os.flush();
sock.close();
}
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 40


Shri Shankaracharya Technical Campus

Client

Algorithm:-
Step 1: Start the program.
Step 2: Create socket.
Step 3: Receive file from server.
Step 4: Close socket.
Step 5: Stop the program.

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;

publicclass TCPFileTransferClient {

publicstaticvoid main(String[] argv)throws Exception {


Socket sock =new Socket("127.0.0.1",1234);
System.out.println("Connected to server");
byte[] mybytearray =newbyte[1024];
InputStream is = sock.getInputStream();
FileOutputStream fos =new FileOutputStream("E://copy.oxps");
BufferedOutputStream bos =new BufferedOutputStream(fos);
int bytesRead;
System.out.println("Receiving file ");
while((bytesRead = is.read(mybytearray))!=-1){
bos.write(mybytearray,0, bytesRead);
}
System.out.println("File Copied Successfully");
bos.close();
sock.close();
}

Output
Server
Waiting for client
Sending file data to client
Sent file successfully to client
Waiting for client
Client
Connected to server
Receiving file
File Copied Successfully

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 41


Shri Shankaracharya Technical Campus

Experiment No.13
Write a client and server program to implement the remote command execution.

Server

Algorithm:-
Step 1: Start the program.
Step 2: Create server socket.
Step 3: accept client Connection.
Step 4: Get command from client.
Step 5: Return output of command to client.
Step6: Close the socket.
Step7: Stop the program.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

publicclass TCPRemoteCommandServer {

privatestatic Socket socket;

publicstaticvoid main(String[] args){


try{

int port =25000;


ServerSocket serverSocket =new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");

//Server is running always. This is done using this while(true) loop


while(true){
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr =new InputStreamReader(is);
BufferedReader br =new BufferedReader(isr);
String command = br.readLine();
System.out.println("Command received from client is "+ command);
String returnMessage;
Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 42
Shri Shankaracharya Technical Campus

TCPRemoteCommandServer ss =new TCPRemoteCommandServer();


returnMessage = ss.executeCommand(command);
System.out.println("Command output "+ returnMessage);
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw =new OutputStreamWriter(os);
BufferedWriter bw =new BufferedWriter(osw);
bw.write(returnMessage);
bw.flush();
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
socket.close();
}catch(Exception e){
}
}
}

private String executeCommand(String command){


StringBuffer output =new StringBuffer();
try{
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =new BufferedReader(
new InputStreamReader(p.getInputStream())
);
String line;
while((line = reader.readLine())!=null){
output.append(line).append("\n");
}

}catch(IOException e1){
}catch(InterruptedException e2){
}
return output.toString();
}
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 43


Shri Shankaracharya Technical Campus

Client

Algorithm:-
Step 1: Start the program.
Step 2: Create socket.
Step 3: Send command to server.
Step 4: Receive output of command from server.
Step 5: Close socket.
Step 6: Stop the program.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

publicclass TCPRemoteCommandClient {

privatestatic Socket socket;

publicstaticvoid main(String args[]){


try{
String host ="localhost";
int port =25000;
InetAddress address = InetAddress.getByName(host);
socket =new Socket(address, port);

//Send the message to the server


OutputStream os = socket.getOutputStream();
OutputStreamWriter osw =new OutputStreamWriter(os);
BufferedWriter bw =new BufferedWriter(osw);

String cmd ="cmd /c ver";

String sendMessage = cmd +"\n";


bw.write(sendMessage);
bw.flush();
System.out.println("Command sent to the server : "+ sendMessage);

//Get the return message from the server


InputStream is = socket.getInputStream();
InputStreamReader isr =new InputStreamReader(is);
BufferedReader br =new BufferedReader(isr);
String line;

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 44


Shri Shankaracharya Technical Campus

//line = br.readLine();
while((line = br.readLine())!=null){
System.out.println(line);
}
System.out.println("Command output received from the server :\n "+ line);
}catch(Exception exception){
exception.printStackTrace();
}finally{
//Closing the socket
try{
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}

Output

Server
Server Started and listening to the port 25000
Command received from client is cmd /c ver
Command output
Microsoft Windows [Version 6.3.9600]
Client
Command sent to the server : cmd /c ver

Microsoft Windows [Version 6.3.9600]

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 45


Shri Shankaracharya Technical Campus

Experiment No.14
Write a client program that gets a number from the user and sends the number to server for converting it
into words gets the result from the server in TCP. (For example if we enter 86 then server will return
Eighty Six).

Server

Algorithm:-
Step 1: Start the program.
Step 2: Create server socket.
Step 3: accept client Connection.
Step 4: Get number from client.
Step 5: Return in words to client.
Step6: Close the socket.
Step7: Stop the program.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

publicclass TCPWordConverterServer {

privatestatic Socket socket;

publicstaticvoid main(String[] args){


try{

int port =25001;


ServerSocket serverSocket =new ServerSocket(port);
System.out.println("Server Started and listening to the port 25001");

//Server is running always. This is done using this while(true) loop


while(true){
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr =new InputStreamReader(is);
BufferedReader br =new BufferedReader(isr);
String number = br.readLine();
System.out.println("Number received from client is "+ number);

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 46


Shri Shankaracharya Technical Campus

//Multiplying the number by 2 and forming the return message


String returnMessage;
try{
int numberInIntFormat = Integer.parseInt(number);
returnMessage = EnglishNumberToWords.convert(numberInIntFormat);
returnMessage = returnMessage +"\n";
}catch(NumberFormatException e){
//Input was not a number. Sending proper message back to client.
returnMessage ="Please send a proper number\n";
}

//Sending the response back to the client.


OutputStream os = socket.getOutputStream();
OutputStreamWriter osw =new OutputStreamWriter(os);
BufferedWriter bw =new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("In words sent to the client is "+ returnMessage);
bw.flush();
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
socket.close();
}catch(Exception e){
}
}
}
}

EnglishNumberToWords.java

import java.text.DecimalFormat;
import java.text.DecimalFormat;

publicclass EnglishNumberToWords {

privatestaticfinal String[] tensNames ={


"",
" ten",
" twenty",
" thirty",
" forty",
" fifty",
" sixty",
" seventy",
" eighty",
" ninety"
Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 47
Shri Shankaracharya Technical Campus

};

privatestaticfinal String[] numNames ={


"",
" one",
" two",
" three",
" four",
" five",
" six",
" seven",
" eight",
" nine",
" ten",
" eleven",
" twelve",
" thirteen",
" fourteen",
" fifteen",
" sixteen",
" seventeen",
" eighteen",
" nineteen"
};

public EnglishNumberToWords(){
}

privatestatic String convertLessThanOneThousand(int number){


String soFar;

if(number %100<20){
soFar = numNames[number %100];
number /=100;
}else{
soFar = numNames[number %10];
number /=10;

soFar = tensNames[number %10]+ soFar;


number /=10;
}
if(number ==0){
return soFar;
}
return numNames[number]+" hundred"+ soFar;
}

publicstatic String convert(long number){

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 48


Shri Shankaracharya Technical Campus

// 0 to 999 999 999 999


if(number ==0){
return"zero";
}

String snumber = Long.toString(number);

// pad with "0"


String mask ="000000000000";
DecimalFormat df =new DecimalFormat(mask);
snumber = df.format(number);

// XXXnnnnnnnnn
int billions = Integer.parseInt(snumber.substring(0,3));
// nnnXXXnnnnnn
int millions = Integer.parseInt(snumber.substring(3,6));
// nnnnnnXXXnnn
int hundredThousands = Integer.parseInt(snumber.substring(6,9));
// nnnnnnnnnXXX
int thousands = Integer.parseInt(snumber.substring(9,12));

String tradBillions;
switch(billions){
case0:
tradBillions ="";
break;
case1:
tradBillions = convertLessThanOneThousand(billions)
+" billion ";
break;
default:
tradBillions = convertLessThanOneThousand(billions)
+" billion ";
}
String result = tradBillions;

String tradMillions;
switch(millions){
case0:
tradMillions ="";
break;
case1:
tradMillions = convertLessThanOneThousand(millions)
+" million ";
break;
default:
tradMillions = convertLessThanOneThousand(millions)
+" million ";

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 49


Shri Shankaracharya Technical Campus

}
result = result + tradMillions;

String tradHundredThousands;
switch(hundredThousands){
case0:
tradHundredThousands ="";
break;
case1:
tradHundredThousands ="one thousand ";
break;
default:
tradHundredThousands = convertLessThanOneThousand(hundredThousands)
+" thousand ";
}
result = result + tradHundredThousands;

String tradThousand;
tradThousand = convertLessThanOneThousand(thousands);
result = result + tradThousand;

// remove extra spaces!


return result.replaceAll("^\\s+","").replaceAll("\\b\\s{2,}\\b"," ");
}
}

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 50


Shri Shankaracharya Technical Campus

Client

Algorithm:-
Step 1: Start the program.
Step 2: Create socket.
Step 3: Send number to server.
Step 4: Receive in word of number from server.
Step 5: Close socket.
Step 6: Stop the program.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

publicclass TCPWordClient {
privatestatic Socket socket;

publicstaticvoid main(String args[]){


try{
String host ="localhost";
int port =25001;
InetAddress address = InetAddress.getByName(host);
socket =new Socket(address, port);

//Send the message to the server


OutputStream os = socket.getOutputStream();
OutputStreamWriter osw =new OutputStreamWriter(os);
BufferedWriter bw =new BufferedWriter(osw);

String number ="253";

String sendMessage = number +"\n";


bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+ sendMessage);

//Get the return message from the server


InputStream is = socket.getInputStream();
InputStreamReader isr =new InputStreamReader(is);
BufferedReader br =new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : "+ message);

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 51


Shri Shankaracharya Technical Campus

}catch(Exception exception){
exception.printStackTrace();
}finally{
//Closing the socket
try{
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}

Output

Server
Server Started and listening to the port 25001
Number received from client is 253
In words sent to the client is two hundred fifty three

Client
Message sent to the server : 253

Message received from the server : two hundred fifty three

Sonu Agrawal, Associate Professor, CSE, SSTC Bhilai Page 52

You might also like