Está en la página 1de 28

National Institute Of Technology, Raipur

Department of Computer Science & Engineering

Lab File
CS 20722(CS)

Network Programming Lab


Autumn Session, 2015

Course B.Tech(NIT Scheme)

Name: NAVEEN KUMAR


Roll Number: 12115048

Semester- 7th Sem.

INDEX
S.No
1.
2.

3.

Name of The Experiment


Write a program which takes a text file
as an input and generate the tokens
using split method
Write a program to which takes a text
file as an input and generate tokens
using StringTokenizer class.
Write a program which takes a text file
as an input and extract the numbers
from it and calculate the sum of these
using Scanner class

Page
No.

Date of
Exp.

Date of
Sub.

05/08/15

08/10/15

05/08/15

08/10/15

05/08/15

08/10/15

4.

Write a program to count the number of


tokens of different data types

05/08/15

08/01/15

5.

Write a program to implement TCP


Socket Programming in Java.

13

12/08/15

08/10/15

6.

Write a program to send file from server


to client using TCP Socket
programming.

16

12/08/15

08/10/15

7.

Write a program to implement UDP


Socket Programming in java

21

12/08/15

08/10/15

8.

Write a program to implement RMI in


Java.

24

23/09/15

08/10/15

9.

Write a program to display System


Variables.

25

23/09/15

08/10/15

10.

Write a program to implement URL


programming in Java.

29

23/09/15

08/10/15

Remarks

EXPERIMENT -1
AIM: Write a program which takes a text file as an input and generate the tokens using split method.
DESCRIPTION:
The java.lang.String.split(String regex, int limit) method splits this string around matches of the
given regular expression. The array returned by this method contains each substring of this string that is
terminated by another substring that matches the given expression or is terminated by the end of the string.
If the expression does not match any part of the input then the resulting array has just one element, namely
this string.
CODE:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args)
{
String st = null;
BufferedReader br;
try {
br = new BufferedReader(new FileReader("C:/nplab/Hello.txt"));
StringBuilder sb = new StringBuilder();
String ln = br.readLine();
while (ln != null) {
sb.append(ln);
sb.append(System.lineSeparator());
ln = br.readLine();
}
st= sb.toString();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(str);
System.out.println("Using String class");
String delims = " ";
String[] tokens1 = str.split(delims);

for (int i = 0; i < tokens1.length; i++)


System.out.println(tokens1[i]);
}
}

OUTPUT:

EXPERIMENT 2
AIM: Write a program to which takes a text file as an input and generate tokens using StringTokenizer class.
DESCRIPTION:
The java.util.StringTokenizer class allows to break a string into tokens. It is simple way to break
string. StringTokenizer(String str, String delim) constructor creates StringTokenizer with specified string and
delimeter.
boolean hasMoreElements(): Checks if there is more tokens available.
Object nextElement(): Returns the next token from the StringTokenizer object.
CODE:
package stringtokens;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args)
{
String st = null;
BufferedReader br;
try {
br = new BufferedReader(new FileReader("E:/nplab/Hello.txt"));
StringBuilder sb = new StringBuilder();
String ln = br.readLine();
while (line != null) {
sb.append(ln);
sb.append("\n");
ln = br.readLine();
}
st= sb.toString();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(str);
String delims = " ";
System.out.println("Using StringTokenizer class");
StringTokenizer st = new StringTokenizer(str, delims);

while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
}
}

OUTPUT:

EXPERIMENT-3
AIM: Write a program which takes a text file as an input and extract the numbers from it and calculate the
sum of these using Scanner class.
DESCRIPTION:
The Scanner class is a class in java.util, which allows the user to read values of various types.
It breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting
tokens may then be converted into values of different types using the various next methods. hasNext()
method returns true if this scanner has another token in its input. In this program nextInt() and
nextDouble() methods have been used to extract the numbers and then the addition is performed.
CODE:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Main
{
public static void main(String[] args) throws FileNotFoundException
{
File f=new File("E:/nplab/Hello.txt");
Scanner sc=new Scanner(f);
int i;
double d,sum=0;
while(sc.hasNext())
{
if(sc.hasNextInt())
{
sum+=sc.nextInt();
}
else if(sc.hasNextDouble())
{
sum+=sc.nextDouble();
}
else
{
String s=sc.next();}
}
System.out.println("Sum = "+sum);
}
}

OUTPUT:

EXPERIMENT 4
AIM: Write a program to count the number of tokens of different data types.
DESCRIPTION:
The java.util.Scanner class is a simple text scanner which can parse primitive types. A Scanner
breaks its input into tokens using a delimiter pattern, which by default matches whitespace. A scanning
operation may block waiting for input. A Scanner is not safe for multithreaded use without external
synchronization.
boolean hasNextBoolean()
This method returns true if the next token in this scanner's input can be interpreted as a boolean value using
a case insensitive pattern created from the string "true|false".
boolean hasNextInt()
This method returns true if the next token in this scanner's input can be interpreted as an int value in the
default radix using the nextInt() method.
boolean hasNextDouble()
This method returns true if the next token in this scanner's input can be interpreted as a double value using
the nextDouble() method.
String next()
This method finds and returns the next complete token from this scanner.
The HashMap class uses a hashtable to implement the Map interface. This allows the execution time
of basic operations, such as get( ) and put( ), to remain constant even for large sets.
CODE:
package scannercount;
import java.util.*;
public class Main {
public static void main(String[] args)
{
Scanner sc=new Scanner("1 2 3 this is NIT Raipur 1 2 3.5 4 4.5 true false");
HashMap<String,Integer> map=new HashMap<String,Integer>();
int i;
double d;
boolean b;
String str;
while(sc.hasNext())

{
if(sc.hasNextInt())
{
i=sc.nextInt();
if(map.get("int")==null)
map.put("int",1);
else
{ Integer in=new Integer(map.get("int"));
map.put("int",in+1);
}
}
else if(sc.hasNextDouble())
{
d=sc.nextDouble();
if(map.get("double")==null)
map.put("double",1);
else
{ Integer in=new Integer(map.get("double"));
map.put("double",in+1);
}
}
else if(sc.hasNextBoolean())
{
b=sc.nextBoolean();
if(map.get("bool")==null)
map.put("bool",1);
else
{ Integer in=new Integer(map.get("bool"));
map.put("bool",in+1);
}
}
else
{
str=sc.next();
if(map.get("string")==null)
map.put("string",1);
else
{ Integer in=new Integer(map.get("string"));
map.put("string",in+1);
}
}
}
System.out.println("Integer tokens = "+map.get("int")+" Double tokens =
"+map.get("double")+"
Boolean tokens = "+map.get("bool")+" String tokens =
"+map.get("string"));
}
}

OUTPUT:

EXPERIMENT-5
AIM: Write a program to implement TCP Socket Programming in Java.
DESCRIPTION:
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.The following
steps occur when establishing a TCP connection between two computers using sockets.
1. The server instantiates a ServerSocket object, denoting which port number communication is to occur on.
2. The server invokes the accept() method of the ServerSocket class. This method waits until a client
connects to the server on the given port.
3. After the server is waiting, a client instantiates a Socket object, specifying the server name and port
number to connect to.
4. The constructor of the Socket class attempts to connect the client to the specified server and port number.
If communication is established, the client now has a Socket object capable of communicating with the
server.
5.On the server side, the accept() method returns a reference to a new socket on the server that is connected
to the client's socket.
CODE:
1.Server.java
import java.io.*;
import java.net.*;
public class Server
{
private static Socket socket;
public static void main(String[] args)
{
OutputStream os;
try
{
ServerSocket serverSocket = new ServerSocket(6309);
System.out.println("Server Started and listening to the port 6309");
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String num = br.readLine();
System.out.println("Message received from client is "+num);
//Multiplying the number by 2 and forming the return message
String retMsg;
try
{
int intNum = Integer.parseInt(num);

int retVal = intNum*2;


retMsg = String.valueOf(retVal) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
retMsg= "Please send a proper number\n";
}
//Sending the response back to the client.
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(retMsg);
System.out.println("Message sent to the client is "+retMsg);
bw.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}
2.Client.java
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String args[])
{
InputStream is;
OutputStream os;
Socket socket = null;
try
{
socket = new Socket("localhost", 6309);
//Send the message to the server
os = socket.getOutputStream();

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));


String number = "2";
String sendMsg = number + "\n";
bw.write(sendMsg);
bw.flush();
System.out.println("Message sent to the server : "+sendMsg);
//Get the return message from the server
is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String msg= br.readLine();
System.out.println("Message received from the server : " +msg);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}

OUTPUT:
1.Server

2.Client

EXPERIMENT-6
AIM: Write a program to send file from server to client using TCP Socket programming.
DESCRIPTION:
The Java.io.BufferedReader class reads text from a character-input stream, buffering characters so as
to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the
default size may be used.Each read request made of a Reader causes a corresponding read request to be
made of the underlying character or byte stream.
Class Constuctors:
BufferedReader(Reader in)
BufferedReader(Reader in, intsz)
Methods
int read()-This method reads a single character.
int read(char[] cbuf, int off, intlen)-This method reads characters into a portion of an array.
String readLine()-This method reads a line of text
CODE:
1.FromServer.java
import java.io.*;
import java.net.*;
public class FromServer {
public final static int SOCKET_PORT = 9909;
public final static String FILE_TO_SEND = "C:\\Users\\nitr\\Desktop\\NP Lab\\file1.txt";
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket Server = null;
Socket socket = null;
try
{
Server = new ServerSocket(SOCKET_PORT);
while (true)
{
System.out.println("Waiting...");
try
{
socket = Server.accept();
System.out.println("Accepted connection : " + socket);
// send file

File myFile = new File (FILE_TO_SEND);


byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = socket.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
}
finally
{
if (bis != null)
bis.close();
if (os != null)
os.close();
if (socket!=null)
socket.close();
}
}
}
finally
{
if (Server != null)
Server.close();
}
}
}
2.ToClient.java
import java.io.*;
import java.net.*;
public class ToClient {
public final static int SOCKET_PORT = 9909;
public final static String SERVER = "127.0.0.1";
public final static String FILE_TO_RECEIVED = "C:\\Users\\nitr\\Desktop\\NP Lab\\file1copy2.txt";
public final static int FILE_SIZE = 6022386;
public static void main(String[] args) throws Exception{
int bytesRead;
int current = 0;
FileOutputStream fos = null;

BufferedOutputStream bos = null;


Socket socket = null;
try
{
socket = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = socket.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do
{
bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0)
current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File " + FILE_TO_RECEIVED + " downloaded (" + current + " bytes read)");
}
finally
{
if (fos != null)
fos.close();
if (bos != null)
bos.close();
if (socket != null)
socket.close();
}
}
}

OUTPUT:
Server

Client

EXPERIMENT 7
AIM: Write a program to implement UDP Socket Programming in java.
DESCRIPTION:
The DatagramPacket and DatagramSocket classes in the java.net package implement system-independent
datagram communication using UDP.DatagramSocket, DatagramPacket, and MulticastSocket are used to
send and receive packets over network.An application can send and receive DatagramPackets through a
DatagramSocket. DatagramPackets can be broadcast to multiple recipients all listening to a MulticastSocket.
CODE:
1.UDPServer.java
package udpsocket;
import java.net.*;
import java.io.*;
public 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: " + 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);
}
}
}
2.UDPClient.java
package udpsocket;
import java.net.DatagramPacket;
import java.net.*;
import java.io.*;

public class UDPClient


{
public static void main(String args[]) throws Exception
{
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();
}
}
OUTPUT:
UDPServer

UDPClient

EXPERIMENT 8
AIM: Write a program to implement RMI in Java.
DESCRIPTION: The Java Remote Method Invocation (Java RMI) is a Java API that performs the objectoriented equivalent of remote procedure calls (RPC), with support for direct transfer of serialized Java
classes and distributed garbage collection.
The original implementation depends on Java Virtual Machine (JVM) class representation
mechanisms and it thus only supports making calls from one JVM to another. The protocol underlying this
Java-only implementation is known as Java Remote Method Protocol (JRMP
CODE:
1.Adder Interface
import java.rmi.*;
public interface Adder extends Remote
{
public int add(int x,int y)throws RemoteException;
}
2.AdderRemote.java
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class AdderRemote extends UnicastRemoteObject implements Adder
{
AdderRemote() throws RemoteException
{
super();
}
public int add(int x,int y)
{
System.out.println("Adding the numbers ");
return x+y;
}
}
3.MyServer.java
import java.rmi.*;
import java.net.*;
import java.io.*;
public class MyServer
{
public static void main(String args[]) throws RemoteException, MalformedURLException,
NotBoundException
{

try
{
Adder stub=new AdderRemote();
Naming.rebind("rmi://localhost:5000/sonoo",stub);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
4.MyClient.java
import java.rmi.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class MyClient
{
public static void main(String args[]) throws RemoteException, MalformedURLException,
NotBoundException, IOException
{
try
{
Scanner sc = new Scanner(System.in);
System.out.println("give the numbers you want to add");
int x = sc.nextInt();
int y = sc.nextInt();
Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
System.out.println("result =" + stub.add(x,y));
}
catch(Exception e)
{
System.out.println(e);
}
}
}

OUTPUT:

MyServer

MyClient

EXPERIMENT-9
AIM:Write a program to display System Variables.
DESCRIPTION:
Environment variables are a set of dynamic named values that can affect the way
running processes will behave on a computer.They are part of the environment in which a
process runs.
System.getenv(String name) method gets the value of the specified environment
variable. An environment variable is a system-dependent external named value.
Environment variables should be used when a global effect is desired, or when an
external system interface requires an environment variable (such as PATH).
DECLARATION
public static String getenv(String name)
Parameters:
name -This is the name of the environment variable.
Return Value:
This method returns the string value of the variable, or null if the variable is not defined
in the system environment.
CODE:
import java.util.Map;
public class envMap {
public static void main (String[] args) {
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
}
}

OUTPUT:

EXPERIMENT 9
AIM: Write a program to implement URL programming in Java.
DESCRIPTION: URL stands for Uniform Resource Locator and represents a resource
on the World Wide Web, such as a Web page or FTP directory.
This section shows you how to write Java programs that communicate with a URL.
The java.net.URL class represents a URL and has complete set of methods to manipulate
URL in Java.
CODE:
// File Name : URLConnDemo.java
import java.net.*;
import java.io.*;
public class URLConnDemo
{
public static void main(String [] args)
{
try
{
URL url = new URL("http://www.amrood.com");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection)
{
connection = (HttpURLConnection) urlConnection;
}
else
{
System.out.println("Please enter an HTTP URL.");
return;
}
BufferedReader in = new BufferedReader(

new InputStreamReader(connection.getInputStream()));
String urlString = "";
String current;
while((current = in.readLine()) != null)
{
urlString += current;
}
System.out.println(urlString);
}catch(IOException e)
{
e.printStackTrace();
}
}
}
OUTPUT:

También podría gustarte