Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Tcpclient

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 40

EXPT NO:1

DATE:
1. TCP CUSTOM SOCKET

AIM:
Write a java program to communicate client and server.

PROGRAM:

TCPCLIENT :

import java.io.*;
import java.net.*;
public class tcpclient
{
public static void main(String args[])throws Exception
{
Socket soc=new Socket("localhost",3000);
BufferedReader KeyRead=new BufferedReader(new
InputStreamReader(System.in));
OutputStream oStream=soc.getOutputStream();
PrintWriter Pwrite=new PrintWriter(oStream,true);
InputStream iStream=soc.getInputStream();
BufferedReader receiveRead=new BufferedReader(new
InputStreamReader(iStream));
System.out.println("start to type");
String receivemessage,sendmessage;
while(true)
{
sendmessage=KeyRead.readLine();
Pwrite.println("nani:"+sendmessage);
Pwrite.flush();
receivemessage=receiveRead.readLine();
System.out.println(receivemessage);
}
}}
PROGRAM:

TCP SERVER:

import java.io.*;
import java.net.*;
public class tcpserver
{
public static void main(String args[])throws Exception
{
ServerSocket SSoc=new ServerSocket(3000);
Socket soc=SSoc.accept();
BufferedReader KeyRead=new BufferedReader(new
InputStreamReader(System.in));
OutputStream oStream=soc.getOutputStream();
PrintWriter Pwrite=new PrintWriter(oStream,true);
InputStream iStream=soc.getInputStream();
BufferedReader receiveRead=new BufferedReader(new
InputStreamReader(iStream));
System.out.println("start to type");
String receivemessage,sendmessage;
while(true)
{
receivemessage=receiveRead.readLine();
System.out.println("vinay:"+receivemessage);
sendmessage=KeyRead.readLine();
Pwrite.println(sendmessage);
Pwrite.flush();
}
}
}
OUTPUT:

RESULT:

Hence the program is successfully executed.


EXPT NO:2
DATE :

UDP SOCKET
AIM:
Write a java program to communicate client and server.

PROGRAM:

UDP CLIENT:

import java.io.*;
import java.net.*;
public class udpc
{
public static void main(String arg[])throws Exception
{
byte buf[]=new byte[1024];
int cport=3789,sport=3790;
DatagramSocket ServerSoc=new DatagramSocket(cport);
DatagramPacket dp=new DatagramPacket(buf,buf.length);
BufferedReader bufread=new BufferedReader(new
InputStreamReader(System.in));
InetAddress ia=InetAddress.getByName("Localhost");
String message;
System.out.println("client is running");
while(true)
{
message=new String(bufread.readLine());
ServerSoc.send(new
DatagramPacket(message.getBytes(),message.length(),ia,sport));
ServerSoc.receive(dp);
message=new String(dp.getData(),0,dp.getLength());
System.out.println("server:"+message);
}
}
}
PROGRAM:

UDP SERVER:

import java.io.*;
import java.net.*;
public class udps
{
public static void main(String arg[])throws Exception
{
byte buf[]=new byte[1024];
int cport=3789,sport=3790;
DatagramSocket ServerSoc=new DatagramSocket(sport);
DatagramPacket dp=new DatagramPacket(buf,buf.length);
BufferedReader bufread=new BufferedReader(new
InputStreamReader(System.in));
InetAddress ia=InetAddress.getByName("Localhost");
String message;
System.out.println("server is running");
while(true)
{
ServerSoc.receive(dp);
message=new String(dp.getData(),0,dp.getLength());
System.out.println("client:"+message);
message=new String(bufread.readLine());
ServerSoc.send(new
DatagramPacket(message.getBytes(),message.length(),ia,cport));
}
}
}
OUTPUT:

RESULT:

Hence the program is successfully executed.


EXPT NO:3
DATE:
MULTICAST UDP SOCKET

AIM:
Write a java program to communicate from multiple clients to server.

PROGRAM:

MULTICAST CLIENT:

import java.io.*;
import java.net.*;
public class msend
{
public static void main(String args[])throws IOException
{
byte buff[]=new byte[1024];
DatagramSocket socket=new DatagramSocket();
InetAddress group=InetAddress.getByName("230.1.1.1");
BufferedReader buffread=new BufferedReader(new
InputStreamReader(System.in));
while(true)
{
String message=buffread.readLine();
buff=message.getBytes();
socket.send(new DatagramPacket(buff,message.length(),group,12345));
}
}
}

MULTICAST RECEIVER:

import java.io.*;
import java.net.*;
public class mrec
{
public static void main(String args[])throws IOException
{
InetAddress maddr=InetAddress.getByName("230.1.1.1");
MulticastSocket msocket=new MulticastSocket(12345);
msocket.joinGroup(maddr);
DatagramPacket packet=new DatagramPacket(new byte[1024],1024);
while(true)
{
msocket.receive(packet);
String message=new
String(packet.getData(),packet.getOffset(),packet.getLength());
System.out.println(message);
}
}
}
OUTPUT:

RESULT:

Hence the program is successfully executed.


EXPT NO: 4
DATE:
URL Class

AIM
Write a java program to To demonstrate the various functions available as
part of URL class.

PROGRAM:

import java.net.MalformedURLException;
import java.net.URL;
public class URLReader
{
public static void main(String[] args)
throws MalformedURLException
{
// creates a URL with string representation.
URL url1 =
new
URL("https://www.google.co.in/?gfe_rd=cr&ei=ptYq""WK26I4fT8gfth6CACg#q
=geeks+for+geeks+java");
// creates a URL with a protocol,hostname,and path
URL url2 = new URL("http", "www.geeksforgeeks.org",
"/jvm-works-jvm-architecture/");
URL url3 = new URL("https://www.google.co.in/search?"+
"q=gnu&rlz=1C1CHZL_enIN71" +
"4IN715&oq=gnu&aqs=chrome..69i57j6" +
"9i60l5.653j0j7&sourceid=chrome&ie=UTF" +
"-8#q=geeks+for+geeks+java");
//URL url3 = new URL("http://saveethaengineering.com/departments/");
// print the String representation of the URL.System.out.println(url1.toString());
System.out.println(url2.toString());
System.out.println();
System.out.println("Different components of the URL3-");
// retrieve the protocol for the URL
System.out.println("Protocol:- " + url3.getProtocol());
// retrieve the hostname of the url
System.out.println("Hostname:- " + url3.getHost());
// retrieve the defalut port
System.out.println("Default port:- " +
url3.getDefaultPort());
// retrieve the query part of URL
System.out.println("Query:- " + url3.getQuery());
// retrive the path of URL
System.out.println("Path:- " + url3.getPath());
// retrive the file name
System.out.println("File:- " + url3.getFile());
// retrieve the reference
System.out.println("Reference:- " + url3.getRef());
}
}
OUTPUT:

RESULT:

Hence the program is successfully executed.


EXPT NO:5
DATE:

CLIENT – SERVER INTERACTION USING RMI

AIM:

Write a java program to demonstrate the interaction of client and server


using remote method invocation (RMI).

PROGRAM:

INTERFACE:

import java.rmi.*;

public interface Adder extends Remote

public int add(int x,int y)throws RemoteException;

ADDER REMOTE.JAVA

import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements Adder{
AdderRemote()throws RemoteException{
super();
}
public int add(int x,int y){
return x+y;
}
}
MYSERVER.JAVA:

import java.rmi.*;
import java.rmi.registry.*;
public class MyServer{public static void main(String args[]){
try{
Adder stub=new AdderRemote();
Naming.rebind("rmi://localhost:5000/sonoo",stub);
}catch(Exception e){System.out.println(e);}
}
}

MYCLIENT.JAVA:

import java.rmi.*;
public class MyClient{
public static void main(String args[]){
try{
Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
System.out.println(stub.add(34,4));
}catch(Exception e){}
}
}
OUTPUT:

RESULT:

Hence the program is successfully executed.


EXPT NO:06

DATE:
CORBA IMPLEMENTATION USING IDL

AIM:
Write a java program to demonstrate the working of CORBA by
establishing a client server interaction.

PROGRAM:

Hello.idl:

module HelloApp
{
interface Hello
{
string sayHello();
oneway void shutdown();
};
};

HelloServer.java:

import HelloApp.*;

import org.omg.CosNaming.*;

import org.omg.CosNaming.NamingContextPackage.*;

import org.omg.CORBA.*;

import org.omg.PortableServer.*;

import org.omg.PortableServer.POA;

import java.util.Properties;
class HelloImpl extends HelloPOA {

private ORB orb;

public void setORB(ORB orb_val) {

orb = orb_val;}

// implement sayHello() method

public String sayHello() {

return "\nHello world !!\n";

// implement shutdown() method

public void shutdown() {

orb.shutdown(false);

public class HelloServer {

public static void main(String args[]) {

try{.

// create and initialize the ORB

ORB orb = ORB.init(args, null);

// get reference to rootpoa & activate the POAManager

POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));

rootpoa.the_POAManager().activate();

// create servant and register it with the ORB


HelloImpl helloImpl = new HelloImpl();

helloImpl.setORB(orb);

// get object reference from the servant

org.omg.CORBA.Object ref = rootpoa.servant_to_reference(helloImpl);

Hello href = HelloHelper.narrow(ref);

// get the root naming context

org.omg.CORBA.Object objRef =

orb.resolve_initial_references("NameService");

// Use NamingContextExt which is part of the Interoperable

// Naming Service (INS) specification.

NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

// bind the Object Reference in Naming

String name = "Hello";

NameComponent path[] = ncRef.to_name( name );

ncRef.rebind(path, href);System.out.println("HelloServer ready and waiting ...");

// wait for invocations from clients

orb.run();

catch (Exception e) {

System.err.println("ERROR: " + e);

e.printStackTrace(System.out);

}
System.out.println("HelloServer Exiting ...");

HelloClient.java:

import HelloApp.*;

import org.omg.CosNaming.*;

import org.omg.CosNaming.NamingContextPackage.*;

import org.omg.CORBA.*;

public class HelloClient

static Hello helloImpl;

public static void main(String args[])

try{

// create and initialize the ORB

ORB orb = ORB.init(args, null);

// get the root naming context

org.omg.CORBA.Object objRef =

orb.resolve_initial_references("NameService");

// Use NamingContextExt instead of NamingContext. This is


// part of the Interoperable naming Service.

NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

// resolve the Object Reference in Naming

String name = "Hello";

helloImpl =
HelloHelper.narrow(ncRef.resolve_str(name));System.out.println("Obtained a
handle on server object: " + helloImpl);

System.out.println(helloImpl.sayHello());

//helloImpl.shutdown();

} catch (Exception e) {

System.out.println("ERROR : " + e) ;

e.printStackTrace(System.out);

}
OUTPUT:

RESULT:

Hence the program is successfully executed.


EXPT NO:7

DATE:

SIMPLE JDBC USING PREPARED STATEMENT

AIM:

Write a java program to demonstrate a simple JDBC program using


prepared statements.

PROGRAM:

import java.io.*;
import java.sql.*;
public class Insert
{
public static void main(String arg[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/hospital";
Connection con=DriverManager.getConnection(url,"root","123456");
String sql="insert into doctor1(name,id,phoneno,dept,exp)values(?,?,?,?,?)";
PreparedStatement pst=con.prepareStatement(sql);
pst.setString(1,"VINAY");
pst.setString(2,"120");
pst.setString(3,"97128249");
pst.setString(4,"anisthesia");
pst.setString(5,"4");
int row=pst.executeUpdate();
if(row>0)
System.out.println("success");
con.close();
}catch(Exception e){System.out.println(e);}
}
}

OUTPUT:

RESULT:

Hence the program is successfully executed.


EXPT NO:08
DATE:

JDBC STORED PROCEDURE INVOCATION

AIM:
Write a java program to demonstrate the jdbc program for JDBC Stored
Procedure invocation using callable statement.

PROGRAM:
import java.sql.*;

public class select


{

public static void main(String[] args)


{
try
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/hospital";
Connection con=DriverManager.getConnection(url,"root","123456");
String query = "SELECT * FROM doctor1";

Statement st = con.createStatement();

ResultSet rs = st.executeQuery(query);

while (rs.next())
{
String name= rs.getString("name");
String id= rs.getString("id");
String phoneno = rs.getString("phoneno");
String dept= rs.getString("dept");
String exp= rs.getString("exp");
System.out.format("%s, %s, %s, %s, %s,\n", name, id,phoneno,dept,exp);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}

OUTPUT:

RESULT:

Hence the program is successfully executed.


EXPT NO:9
DATE:

SIMPLE SERVLET PROGRAMMING USING TOMCAT


SERVER

AIM:
Write a java program to edemonstrate the java program for Simple servlet
programming using Tomcat server.

PROGRAM:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}public void destroy() {
// do nothing.
}
}
OUTPUT:

RESULT:

Hence the program is successfully executed.


EXPT NO:10
DATE:

SIMPLE JSP IMPLEMENTATION

AIM:
Write a java program to demonstrate the working of a simple JSP using
Tomcat server.

PROGRAM:

Register:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Form</title>
</head>
<body>
<h1>Register Form</h1>
<form action="RegisterNow" method="post">
<table style="with: 50%">
<tr>
<td>First Name</td>
<td><input type="text" name="first_name" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="last_name" /></td>
</tr>
<tr>
<td>UserName</td><td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" /></td>
</tr>
<tr>
<td>Contact No</td>
<td><input type="text" name="contact" /></td>
</tr></table>
<input type="submit" value="Submit" /></form>
</body>
</html>

Registernow:

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class guru_register
*/
public class RegisterNow extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws
ServletException, IOException {
// TODO Auto-generated method stub
String first_name = request.getParameter("first_name");
String last_name = request.getParameter("last_name");
String username = request.getParameter("username");
String password = request.getParameter("password");
String address = request.getParameter("address");
String contact = request.getParameter("contact");
if(first_name.isEmpty() || last_name.isEmpty() || username.isEmpty()
||password.isEmpty() || address.isEmpty() || contact.isEmpty())
{
RequestDispatcher req = request.getRequestDispatcher("Register.jsp");
req.include(request, response);
}
else
{
RequestDispatcher req = request.getRequestDispatcher("WelcomePage.jsp");
req.forward(request, response);
}
}
}

Welcome page:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome Page</title>
</head>
<body>
<a><b>Welcome User!!!!</b></a>
</body>
</html>

OUTPUT:
REGISTER PAGE:
WELCOME FORM:

RESULT:

Hence the program is successfully executed.


EXPNO:11

DATE:

INTER APPLET COMMUNICATION

AIM:

Write a java program to demonstrate the java program for inter applet
communication.

PROGRAM:

APPLET1:
/**
<Applet code="Appletcom1.class" name="Appletcom1"height=800 width=800>
</applet>
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Appletcom1 extends Applet implements ActionListener
{
TextField tf;
Button b;
public void init()
{
tf=new TextField(25);
b=new Button("communicate");
b.addActionListener(this);
add(tf);
add(b);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() instanceof Button)
{
String message=tf.getText().trim();
Appletcom2
ap=(Appletcom2)getAppletContext().getApplet("applet communication");
if(ap!=null)
{
ap.add(message);
}
else
{
System.out.println("applet communication not found");
}
}
}
}

APPLET2:

/**<Applet code="Appletcom2.class" name="Appletcom2" height=800


width=800>
</applet>
*/
import java.applet.*;
import java.awt.*;
public class Appletcom2 extends Applet
{
TextArea tf;
public void init()
{
tf=new TextArea(7,20);
add(tf);
}
public void add(String msg)
{
tf.append(msg);
tf.append("\n");
}
}
HTML CODE:

<html>
<body>
<applet code="InterAppletCommunication1"
name="InterAppletCommunication1"
height="300" width="350"></applet>
<applet code="InterAppletCommunication2"
name="InterAppletCommunication2"
height="300" width="350"></applet>
</body>
</html>

OUTPUT:

BEFORE COMMUNICATION:
AFTER COMMUNICATION:

RESULT:

Hence the program is successfully executed.


EXPT NO:12
DATE:15/11/2017
SIMPLE EJB PROGRAM
AIM:
Write a java program to demonstrate and implement a Simple EJB
program.

PROGRAM:

import com.tutorialspoint.stateless.LibrarySessionBeanRemote;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class EJBTester {


BufferedReader brConsoleReader = null;
Properties props;
InitialContext ctx;
{
props = new Properties();
try {
props.load(new
FileInputStream("jndi.properties")); }
catch (IOException ex) {
ex.printStackTrace();
}
try {
ctx = new InitialContext(props);
} catch (NamingException ex) {

ex.printStackTrace();
}
brConsoleReader =
new BufferedReader(new InputStreamReader(System.in));
}
public static void main(String[] args) {

EJBTester ejbTester = new EJBTester();

ejbTester.testStatelessEjb();
}
private void showGUI(){
System.out.println("**********************");
System.out.println("Welcome to Book Store");
System.out.println("**********************");
System.out.print("Options \n1. Add Book\n2. Exit \nEnter Choice: ");
}
private void testStatelessEjb(){
try {
int choice = 1;
LibrarySessionBeanRemote libraryBean =
(LibrarySessionBeanRemote)ctx.lookup("LibrarySessionBean/remote");
while (choice != 2) {
String bookName;
showGUI();
String strChoice = brConsoleReader.readLine();
choice = Integer.parseInt(strChoice);
if (choice == 1) {
System.out.print("Enter book name: ");
bookName = brConsoleReader.readLine();
libraryBean.addBook(bookName);
}else if (choice == 2) {
break;
}
}
List<String> booksList = libraryBean.getBooks();
System.out.println("Book(s) entered so far: " +
booksList.size()); for (int i = 0; i <
booksList.size(); ++i) {
System.out.println((i+1)+". " + booksList.get(i));
}
LibrarySessionBeanRemote libraryBean1 =
(LibrarySessionBeanRemote)ctx.lookup("LibrarySession
Bean/remote"); List<String> booksList1 =
libraryBean1.getBooks(); System.out.println(

"***Using second lookup to get library


stateless object***"); System.out.println(
"Book(s) entered so far: " + booksList1.size());
for (int i = 0; i < booksList1.size(); ++i) {
System.out.println((i+1)+". " + booksList1.get(i));
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}finally {
try {
if(brConsoleReader !=null){
brConsoleReader.close();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}

OUTPUT:

RESULT:

Hence the program is successfully executed.

You might also like