Você está na página 1de 24

Client / Server Lab Program details

1. Develop a program to display the time of the server from a client using TCP/IP
2. Develop a program to display the time of the server from a client using UDP
3. Develop a client/server application for chat using TCP/IP
4. Develop a client/server application for chat using UDP
5. Write a program to simulate Domain Name Server
6. Write a client program to download a file from HTTP server
7. Implement a RPC
8. Implement a FTP
9. Develop a client/server application for E-mails
10. Develop a client/server Banking Application with database connectivity
11. Develop a client/server reservation system application with database connectivity
12. Develop a client/server application for implementing a scheduling for printing a different
jobs based on priority

1. Develop a program to display the time of the server from a client using TCP/IP
ALGORITHM:Step1: Start the program
Step2: Create the TCP sockets for communications between Client and Server.
Step3: Get the time from the server using the server socket.
Step4: Send the time and date format to the client side.
Step5: Print the Date and the Time.
Step6: Stop the program.

tcptimeserver.java
import java.io.*;
import java.net.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class tcptimeserver
{
public static void main(String a[]) throws Exception
{
String DATE_FORMAT_NOW="yyyy-MM-dd HH:mm:ss";
System.out.println("TCP SERVER");

System.out.println("Server is ready to send time......");


ServerSocket serversoc = new ServerSocket(9);
Socket clientsoc =serversoc.accept();
PrintWriter out=new PrintWriter(clientsoc.getOutputStream(),true);
String inputline;
Calendar cal= Calendar.getInstance();
SimpleDateFormat sdf=new SimpleDateFormat(DATE_FORMAT_NOW);
inputline=sdf.format(cal.getTime());
out.println(inputline);
System.out.println("Process finished");
}
}

tcptimeclient.java
import java.io.*;
import java.net.*;
public class tcptimeclient
{
public static void main(String[] args) throws IOException
{
System.out.println("TCP CLIENT");
System.out.println("Enter the host name to connect");
DataInputStream inp=new DataInputStream(System.in);
String str=inp.readLine();
Socket clientsoc=new Socket(str,9);
PrintWriter out=new PrintWriter(clientsoc.getOutputStream(),true);
BufferedReader in=new BufferedReader(new InputStreamReader(clientsoc.getInputStream()));

System.out.println("Server Says: "+in.readLine());


}
}

2. Develop a program to display the time of the server from a client using UDP
ALGORITHM:Step1: Start the program
Step2: Create the UDP Sockets for communication between the Client and the Server.
Step3: Get the time from the server using the UDP Server socket.
Step4: Send the time and date format to the client side.
Step5: Print the Date and the Time.
Step6: Stop the program.

UDPServer.java
import java.net.*;
import java.io.*;
import java.util.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket dsoc=new DatagramSocket(5217);
InetAddress host=InetAddress.getLocalHost();
String str=(new Date()).toString();
byte buf[]=str.getBytes();
dsoc.send(new DatagramPacket(buf,buf.length,host,24));
dsoc.close();
}
}

UDPClient.java
import java.net.*;
import java.io.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
DatagramSocket dsoc=new DatagramSocket(24);
byte buff[]=new byte[1024];
DatagramPacket dpack=new DatagramPacket(buff,buff.length);
dsoc.receive(dpack);
System.out.println(new String(dpack.getData()));
}
}

3. Develop a client/server application for chat using TCP/IP


ALGORITHM:Step1: Start the program
Step2: Create the TCP sockets for communications between Client and Server.
Step3: Establish the connections between the client and the server using the following
functions.
Socket clientsoc=serversoc.accept();
Step4: Send message from the server to that of the client side.
Step5: Accept the message from the server and send the reply message from the client to the
server
Step6: Close the connections between the client and server.
Step7: Stop the program.

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

public class tcpserver


{
public static void main(String a[]) throws Exception
{
System.out.println("TCP CLIENT");
System.out.println("Server is ready to connect....");
ServerSocket serversoc=new ServerSocket(9);
Socket clientsoc=serversoc.accept();
PrintWriter out=new PrintWriter(clientsoc.getOutputStream(),true);
BufferedReader in= new BufferedReader(new InputStreamReader(clientsoc.getInputStream()));
String inputline;
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
try
{
while(true)
{
inputline=stdin.readLine();
out.println(inputline);
System.out.println("Client says: "+in.readLine());
}
}
catch(Exception e)
{
System.exit(0);
}
}
}

tcpclient.java
import java.io.*;
import java.net.*;
public class tcpclient
{
public static void main(String[] args) throws IOException
{
System.out.println("TCP CLIENT");
System.out.println("Enter the host name to connect");
DataInputStream inp=new DataInputStream(System.in);
String str=inp.readLine();
Socket clientsoc=new Socket(str,9);
PrintWriter out=new PrintWriter(clientsoc.getOutputStream(),true);
BufferedReader in=new BufferedReader(new InputStreamReader(clientsoc.getInputStream()));
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String userinput;
try
{
while(true)
{
System.out.println("Server says:"+in.readLine());
userinput=stdin.readLine();
out.println(userinput);
}
}
catch(Exception e)

{
System.exit(0);
}
}
}

4. Develop a client/server application for chat using UDP


ALGORITHM:Step1: Start the program
Step2: Create the UDP sockets for communications between Client and Server.
Step3: Establish the connections between the client and the server using the following
functions.
String sentence=new String(receivePacket.getData());
Step4: Send message from the server to that of the client side.
Step5: Accept the message from the server and send the reply message from the client to the
server
Step6: Close the connections between the client and server.
Step7: Stop the program.

UDPServer.java
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)

{
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();
DatagramPacket sendPacket=new DatagramPacket(sendData,sendData.length,IPAddress,port);
serverSocket.send(sendPacket);
}
}
}

UDPClient.java
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
while(true)
{
BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket =new DatagramSocket();
InetAddress IPAddress=InetAddress.getByName("localhost");

byte[] sendData=new byte[1024];


byte[] receiveData=new byte[1024];
String sentence = inFromUser.readLine();
sendData=sentence.getBytes();
DatagramPacket sendPacket=new DatagramPacket(sendData,sendData.length,IPAddress,9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket=new DatagramPacket(receiveData,receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
}

5. Write a program to simulate Domain Name Server


ALGORITHM:Step1: Start the program.
Step2: Declare the InetAddress of the particular system.
Step3: Get the host name of the system.
Step4: Print the new Host name and the IP Address.
Step5: Otherwise print the error message as Unknown Host.
Step6: Stop the program.

IPtoDNS.java
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPtoDNS
{
public static void main(String[] args) throws Exception
{
try
{
InetAddress[] addresses=InetAddress.getAllByName("172.16.1.65"/*ip or DNS
name*/);

for(int i=0;i<addresses.length;i++)
{
String hostname=addresses[i].getHostName();
System.out.println("The New Name is : "+hostname);
String s= addresses[i].getHostAddress();
System.out.println(s);
}
}
catch(UnknownHostException e)
{
System.out.println("Unknown Host");
}
}
}

6. Write a client program to download a file from HTTP server


ALGORITHM:Step1: Start the program.
Step2: Create the connection using the following functions.
HttpURLConnection con=(HttpURLConnection)url.openConnection();
Step3: Create a text file named as newfile.txt for storing the content of the Web Address.
Step4: Write the content of the page to the Text file that is already created.
Step5: Print the output and close the connections.
Step6: Stop the program.

main.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class main
{
public static void main(String[] argv) throws Exception
{

URL url=new URL("http://www.server.com");


HttpURLConnection con=(HttpURLConnection)url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
File newfile=new File("newfile.txt");
FileWriter out =new FileWriter(newfile);
while((inputLine=in.readLine())!=null)
{
System.out.println(inputLine);
out.write(inputLine);
}
in.close();
}
}

7. Implementation a FTP
ALGORITHM:Step1: start the program.
Step2: Create the TCP socket for communication between the client and the server.
Step3: Establish the connections between the client and the server.
Step4: Get the Target file to be sent using the FTP Protocol.
Step5: Transfer the Particular file to the client side.
Step6: Receive the file that is transferred from the server side.
Step7: After finishing all the request from the client side close the connection between them.
Step8: Stop the program.

ftpclient.java
import java.net.*;
import java.io.*;
import java.util.*;
class ftpclient

{
public static void main(String args[])throws Exception
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\n\n\n\tFTP");
while(true)
{
Socket s= new Socket(InetAddress.getLocalHost(),9999);
InputStream i=s.getInputStream();
DataInputStream dis=new DataInputStream(i);
OutputStream o=s.getOutputStream();
DataOutputStream dos=new DataOutputStream(o);
System.out.println("Enter the file name");
String fname=in.readLine();
dos.writeUTF(fname);
if(fname.equals("exit"))
{
break;
}
else
{
String st ="1";
System.out.println("The Received File");
try
{
while(!st.equals(-1))
{

st=dis.readUTF().toString();
System.out.println(st);
}
}
catch(Exception ex){}
}
dis.close();
dos.close();
i.close();
s.close();
o.close();
}
}
}

ftpserver.java
import java.net.*;
import java.io.*;
class ftpserver
{
public static void main(String args[])throws Exception
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
ServerSocket ss=new ServerSocket(9999);
while(true)
{
Socket s=ss.accept();

InputStream i=s.getInputStream();
DataInputStream dis=new DataInputStream(i);
OutputStream o=s.getOutputStream();
DataOutputStream dos=new DataOutputStream(o);
System.out.println("Waiting for request");
String fname=dis.readUTF().toString();
if(fname.equals("exit"))
{
s.close();
System.exit(1);
}
else
{
System.out.println("The received file name Is"+fname);
FileReader fr=new FileReader(fname);
BufferedReader br=new BufferedReader(fr);
String sr;
while((sr=br.readLine())!=null)
{
dos.writeUTF(sr);
}
System.out.println("File is");
fr.close();
dis.close();
i.close();
dos.close();
o.close();

s.close();
}
}
}
}

8. Develop a client/server application for E-mails


ALGORITHM:Step1: Start the program.
Step2: Create the web applications using the NETBEANS.
Step3: Now create the EmailServlet using the Raw Socket and the SMTP Protocol.
Step4: Using the SMTP Protocol make the connections between the Email Server to that of the
local system or client that you are using.
Step5: Create an interface for sending message to the particular Email Server.
Step6: Create the Java Server Pages for Error and Successful sent mail console process.
Step7: Sent the mail to the Particular Email Server and get the Message from the Server pages.
Step8: Close the connections.
Step9: Stop the program.

EmailServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
/**
* This servlet demonstrates how to send simple email
* using raw socket connections and the SMTP protocol.
* You should use the Java Mail API if you want a more robust
* and reliable delivery.
* - Ken Schweller

*/
public class EmailServlet extends HttpServlet
{
/**
* Bare bones method to send email message. No attempt is
* made to verify delivery. Uses SMTP protocol to contact
* an email server at '147.92.12.24' - port 25
**/
public void sendEmail( String from, String to, String message)
{
try
{
// get a socket connection to the mail
// server at SMTP port 25
Socket socket = new Socket("172.16.1.12", 25);
// Create an output stream for sending message
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// send mail using SMTP protocol
out.println("MAIL FROM: " + from);
out.println("RCPT TO: " + to);
out.println("DATA\n"); // Skip line after DATA
out.println(message);
out.println(".");
// End message with a single period
out.flush();
}
catch (Exception e)
{
System.out.println("Failed to send email: " + e);
}
}

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
String from = request.getParameter("from");

String to
= request.getParameter("to");
String message = request.getParameter("message");
sendEmail(from, to, message);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Email hopefully sent to " + to);
}
}

Success.jsp
<%-Document : success
Created on : Sep 7, 2009, 4:39:17 PM
Author : power
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>Message</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<center>
<div class="msg">
<h2>Message</h2>
<p>
Email sent
</p>
</div>
</center>
</body>
</html>

Index.jsp
<%-Document : index
Created on : Sep 7, 2009, 4:21:36 PM
Author : power
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sending email</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<center>
<form action="EmailServlet">
<table>
<tr>
<td>From</td>
<td><input type="text" name="from"></td>
</tr>
<tr>
<tr>
<td>To</td>
<td><input type="text" name="to"></td>
</tr>
<tr>
<td>Subject</td>
<td><input type="text" name="subject"></td>
</tr>
<tr>
<td>Message</td>
<td><textarea cols="25" rows="8" name="message"></textarea></td>
</tr>
<tr>
<td>Login</td>
<td><input type="text" name="login"></td>

</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
</table>
<br>
<input type="submit" value="submit">
</form>
</center>
</body>
</html>

Error.jsp
<%-Document : error
Created on : Sep 7, 2009, 4:39:39 PM
Author : power
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<center>
<div class="error">
<h2>Error</h2>
<p>
Message: <%= request.getAttribute("ErrorMessage") %>
</p>
</div>
</center>
</body>
</html>

9. Develop a client/server reservation system application with database connectivity


ALGORITHM:Step1: Start the program.
Step2: Initialize the Java DataBase Driver to that of the Object DataBase Driver.
Step3: Create an ODBC Driver for connecting the Access Database.
Step4: Create the Table in the database and add the necessary fields in that table.
Step5: Select the Data Source and link the DataBase to that of the Java program.
Step6: Run the program and insert the Data into the table using the Queries.
Step7: Retrieve the Data from the DataBase and print the result.
Step8: Stop the program.

Main.java
import java.io.DataInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class Main {
Connection connection;
Statement statment;
ResultSet resultset;
public boolean connect(){
boolean status = false;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = java.sql.DriverManager.getConnection("jdbc:odbc:ODBC_AMS");
status = true;
}
catch(Exception e)
{
System.out.println("Error in db connection");
}
return status;
}

public String MakeTickets(String ticket_name,int ticket_number,int ticket_quent,double


ticket_price,String start_location,String end_location)
{
String str="Problem in data insert";
try
{
boolean st = connect();
System.out.println("connection -->"+st);
String add_query = "INSERT INTO
ticket(ticket_number,ticket_name,ticket_quent,ticket_price,start_location,end_location)
VALUES("+ticket_number+",'"+ticket_name+"',"+ticket_quent+","+ticket_price+",'"+start_locat
ion+"','"+end_location+"')";
System.out.println("Insert query-->"+add_query);
java.sql.Statement statement = connection.createStatement();
statement.execute(add_query);
str= "Ticket successfully added" ;
}
catch(Exception e)
{
System.out.println("Error in Insert:"+e);
}
return str;
}

public String reservTicket(int ticket_number,String ticket_name, int ticket_quent)


{
String str="Problem in reserv";
try
{
int qunt=0;
boolean st = connect();
String select_query = "SELECT * FROM ticket WHERE
ticket_number="+ticket_number;
java.sql.Statement statement = connection.createStatement();
statement.executeQuery(select_query);
java.sql.ResultSet resultSet = statement.getResultSet();
if(resultSet.next())
{
qunt = resultSet.getInt("ticket_quent");
}

if(qunt<ticket_quent)
{
return qunt+" tickets only avilable for this rout";
}
else
{
qunt = qunt - ticket_quent;
String update_query = "UPDATE ticket SET ticket_quent="+qunt+" WHERE
ticket_number="+ticket_number;
int status = statement.executeUpdate(update_query);
if(status==1 )
{
return "Ticket successfully Reserved";
}
else
{
return str;
}
}
}
catch(Exception e)
{
System.out.println("Error in reserv: "+e);
}
return "Reservation method";
}
public void InformationCenter(String start_location,String end_location)
{
String str="Problem in information center";
try
{
int qunt=0;
boolean st = connect();
String select_query = "SELECT * FROM ticket WHERE
start_location='"+start_location+"' AND end_location='"+end_location+"'";
System.out.println("Select query -->"+select_query);
java.sql.Statement statement = connection.createStatement();
statement.executeQuery(select_query);
java.sql.ResultSet resultSet = statement.getResultSet();

if(resultSet.next())
{
System.out.println("Ticket Details");
System.out.println("Ticket Number -->"+resultSet.getInt("ticket_number"));
System.out.println("Ticket Name-->"+resultSet.getString("ticket_name"));
System.out.println("Each Ticket Price-->"+resultSet.getDouble("ticket_price"));
System.out.println("Number of Tickets available->"+resultSet.getInt("ticket_quent"));
}
else
{
System.out.println("There is no tickets for this rout");
}
}
catch(Exception e)
{
System.out.println("Error in reserv: "+e);
}
}
public static void main(String[] args) throws IOException
{
DataInputStream din = new DataInputStream(System.in);
Main res = new Main();
while(true){
System.out.println("\t\tOn-line Train-Ticket Reservation ");
System.out.println("1.Make Tickets (Administrator only)\n2.Ticket
Reservation\n3.Imfomation Center\n4.Exit");
System.out.println("Enter your choice :");
int choice = Integer.parseInt(din.readLine());
switch (choice)
{
case 1:
{
System.out.println("Enter Trian Ticket Number:");
int ticket_number = Integer.parseInt(din.readLine());
System.out.println("Enter Ticket Name:");
String ticket_name = din.readLine();
System.out.println("Enter Ticket price :");
double ticket_price= Double.parseDouble(din.readLine());
System.out.println("Start location:");

String start_location = din.readLine();


System.out.println("End location:");
String end_location = din.readLine();
System.out.println("Number of Tickets :");
int ticket_quent =Integer.parseInt(din.readLine());
String output = res.MakeTickets(ticket_name,
ticket_number,ticket_quent,ticket_price, start_location, end_location);
System.out.println(output);
}
break;
case 2:
{
System.out.println("Enter Trian Ticket Number:");
int ticket_number = Integer.parseInt(din.readLine());
System.out.println("Enter Ticket Name:");
String ticket_name = din.readLine();
System.out.println("Number of Tickets :");
int ticket_quent =Integer.parseInt(din.readLine());
String output = res.reservTicket(ticket_number, ticket_name, ticket_quent);
System.out.println(output);
}
break;
case 3:
{
System.out.println("Start location:");
String start_location = din.readLine();
System.out.println("End location:");
String end_location = din.readLine();
res.InformationCenter(start_location, end_location);
}
break;
case 4:
System.exit(1);
break;
}}
}}

Você também pode gostar