100% found this document useful (1 vote)
142 views

Assignment No.1: //WAP To Simulate The Functionality of Lamport's Logical Clock

This document contains code to simulate distributed mutual exclusion across multiple processes. It defines a Node class to represent each process, with methods for choosing a number to enter the critical section, sending requests, waiting for replies, and replying to deferred nodes. Each node runs in its own thread. Request and reply messages are passed asynchronously between nodes using message passing channels. The algorithm ensures only one node is in its critical section at a time by having nodes wait for replies from all other nodes before entering.

Uploaded by

Himal Bhandari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
142 views

Assignment No.1: //WAP To Simulate The Functionality of Lamport's Logical Clock

This document contains code to simulate distributed mutual exclusion across multiple processes. It defines a Node class to represent each process, with methods for choosing a number to enter the critical section, sending requests, waiting for replies, and replying to deferred nodes. Each node runs in its own thread. Request and reply messages are passed asynchronously between nodes using message passing channels. The algorithm ensures only one node is in its critical section at a time by having nodes wait for replies from all other nodes before entering.

Uploaded by

Himal Bhandari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Assignment No.

1
//WAP to simulate the functionality of Lamport's Logical clock

Solutions
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
#include<stdlib.h>
#include<graphics.h>
#include<string.h>
#include<dos.h>

void main(){
int s[4][9],n,m=0;
int i,j,next=0,step=0;
int msg[10][4]={0},totmsg;
char op;
int pi,pj,ei,ej;

clrscr();
cout<<"\nProgram for Lamport Logical Clock";
cout<<"\nEnter Number Of Process ";
cin>>n;
for(i=0;i<n;i++){
cout<<"\nEnter number of STATES of process P"<<i<<" ";
cin>>s[i][8];
for(j=1;j<=s[i][8];j++){
s[i][j]=j;
}
}

do{
cout<<"\nEnter message transit";
cout<<"\nFROM ->\nEnter Process Number P";
cin>>msg[m][0];
cout<<"\nEnter Event Number e";
cin>>msg[m][1];
cout<<"\nTO ->\nEnter Process Number P";
cin>>msg[m][2];
cout<<"\nEnter Event Number e";
cin>>msg[m][3];
cout<<"\n\nPress 'y' to continue";
op=getch();
cout<<op;
m++;
totmsg=m;

}while(op=='y');
m=0;
for (i=0;i<totmsg;i++){
pi=msg[i][0];
ei=msg[i][1];
pj=msg[i][2];
ej=msg[i][3];
if(s[pj][ej]< (s[pi][ei]+1)){
s[pj][ej]=s[pi][ei]+1;
for (j=ej+1;j<=s[pj][8];j++){
s[pj][j]=s[pj][j-1]+1;
}
}
}
int gd=DETECT,gm;
initgraph(&gd,&gm,"C:\\TC\\BGI");
outtextxy(200,15,"Program For Lamport Logical Clock");
//drawing process and events
for(i=0;i<n;i++){
char* p1;
itoa(i,p1,10);
outtextxy(5,100+next,"P");
outtextxy(13,100+next,p1);
line(100,100+next,600,100+next);
for(j=1;j<=s[i][8];j++){
char* p2;
itoa(j,p2,10);
outtextxy(100+step,90+next,"e");
outtextxy(110+step,90+next,p2);
//timestamp
char* p3;
itoa(s[i][j]-1,p3,10);
outtextxy(100+step,110+next,"t");
outtextxy(110+step,110+next,p3);
circle(105+step,100+next,5);
step+=50;
}
step=0;
next+=100;
}
delay(2000);
//drawing message transit
for(m=0;m<totmsg;m++){
setlinestyle(SOLID_LINE,1,3);
setcolor(m+4);

line(msg[m][1]*50+50,msg[m][0]*100+100,msg[m][3]*50+50,msg[m][2]*
100+100);
if (msg[m][2]>msg[m][0]){

line(msg[m][3]*50+50,msg[m][2]*100+100,msg[m][3]*50+50,msg[m][2]*
100+90);

line(msg[m][3]*50+50,msg[m][2]*100+100,msg[m][3]*50+40,msg[m][2]*
100+90);
}
else{
line(msg[m][3]*50+50,msg[m][2]*100+100,msg[m][3]*50+50,msg[m][2]*
100+110);

line(msg[m][3]*50+50,msg[m][2]*100+100,msg[m][3]*50+40,msg[m][2]*
100+110);
}
}
getch();
}
Output
Assignment No.2

//WAP to Implement Vector clock

solution

#include<stdio.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
long *p1(int i,long *comp);
long *p2(int i,long *comp);
long *p3(int i,long *comp);
void main()
{
long start[]={0,0,0},*vector;
clrscr();
while(!kbhit())
{
p1(1,&start[0]);
}
printf("\n Process Vector\n");
vector=p1(0,&start[0]);
printf("p1[%ld%ld%ld]\n",*vector,*(vector+1),*(vector+2));
vector=p2(0,&start[0]);
printf("p2[%ld%ld%ld]\n",*vector,*(vector+1),*(vector+2));
vector=p3(0,&start[0]);
printf("p3[%ld%ld%ld]\n",*vector,*(vector+1),*(vector+2));
}
long *p1(int i,long *comp)
{
static long a[]={0,0,0};
int next;
if(i==1)
{
a[0]++;
if(*(comp+1)>a[1])
a[1]=*(comp+1);
if(*(comp+2)>a[2])
a[2]=*(comp+2);
next=random(2);
if(next==0)
p2(1,&a[0]);
else if(next==1)
p3(1,&a[0]);
return(&a[0]);
}
else
return(&a[0]);
}
long *p2(int i,long *comp)
{
static long b[]={0,0,0};
int next;
if(i==1)
{
b[i]++;
if(*comp>b[0])
b[0]=*(comp);
if(*(comp+2)>b[2])
b[2]=*(comp+2);
next=random(2);
if(next==0)
p1(1,&b[0]);
else if(next==1)
p3(1,&b[0]);
return &b[0];
}
else
return &b[0];
}
long *p3(int i,long *comp)
{
static long c[]={0,0,0};
int next;
if(i==1)
{
c[2]++;
if(*comp>c[0])
c[0]=*(comp);
if(*(comp+1)>c[1])
c[1]=*(comp+1);
next=random(2);
if(next==0)
p1(1,&c[0]);
return &c[0];
}
else
return &c[0];
}
OUTPUT
Assignment No.3

//Simulation of Distributed mutual exclusion

Solutions
import Utilities.*;
import Synchronization.*;

class Message { public int number, id;


public Message(int number, int id) { this.number = number; this.id = id;}
}

class Node extends MyObject implements Runnable {

private static final int MAIN = 0, REQUESTS = 1, REPLIES = 2;


private int whichOne = 0;

private int id = -1;


private int numNodes = -1;
private int napOutsideCS = 0; // both are in
private int napInsideCS = 0; // milliseconds
private MessagePassing[] requestChannel = null;
private MessagePassing[] replyChannel = null;
private MessagePassing requestsToMe = null;
private MessagePassing repliesToMe = null;
private int number = 0;
private int highNumber = 0;
private boolean requesting = false;
private int replyCount = 0;
private BinarySemaphore s = new BinarySemaphore(1);
private BinarySemaphore wakeUp = new BinarySemaphore(0);
private boolean[] deferred = null;

public Node(String name, int id, int numNodes,


int napOutsideCS, int napInsideCS,
MessagePassing[] requestChannel, MessagePassing replyChannel[],
MessagePassing requestsToMe, MessagePassing repliesToMe) {
super(name + " " + id);
this.id = id;
this.numNodes = numNodes;
this.napOutsideCS = napOutsideCS;
this.napInsideCS = napInsideCS;
this.requestChannel = requestChannel;
this.replyChannel = replyChannel;
this.requestsToMe = requestsToMe;
this.repliesToMe = repliesToMe;
deferred = new boolean[numNodes];
for (int i = 0; i < numNodes; i++) deferred[i] = false;
System.out.println(getName() + " is alive, napOutsideCS="
+ napOutsideCS + ", napInsideCS=" + napInsideCS);
new Thread(this).start();
}

public void run() { // start three different threads in the same object
int meDo = whichOne++;
if (meDo == MAIN) {
new Thread(this).start();
main();
} else if (meDo == REQUESTS) {
new Thread(this).start();
handleRequests();
} else if (meDo == REPLIES) {
handleReplies();
}
}

private void chooseNumber() {


P(s);
requesting = true;
number = highNumber + 1;
V(s);
}

private void sendRequest() {


replyCount = 0;
for (int j = 0; j < numNodes; j++) if (j != id)
send(requestChannel[j], new Message(number, id));
}

private void waitForReply() {


P(wakeUp);
}

private void replyToDeferredNodes() {


P(s);
requesting = false;
V(s);
for (int j = 0; j < numNodes; j++) {
if (deferred[j]) {
deferred[j] = false;
send(replyChannel[j], id);
}
}
}

private void outsideCS() {


int napping;
napping = ((int) random(napOutsideCS)) + 1;
System.out.println("age()=" + age() + ", " + getName()
+ " napping outside CS for " + napping + " ms");
nap(napping);
}

private void insideCS() {


int napping;
napping = ((int) random(napInsideCS)) + 1;
System.out.println("age()=" + age() + ", " + getName()
+ " napping inside CS for " + napping + " ms");
nap(napping);
}

private void main() {


while (true) {
outsideCS();
System.out.println("age()=" + age() + ", node " + id
+ " wants to enter its critical section");
chooseNumber(); // PRE-PROTOCOL
sendRequest(); // "
waitForReply(); // "
insideCS();
System.out.println("age()=" + age() + ", node " + id
+ " has now left its critical section");
replyToDeferredNodes(); // POST-PROTOCOL
}
}

private void handleRequests() {


while (true) {
Message m = (Message) receive(requestsToMe);
int receivedNumber = m.number;
int receivedID = m.id;
highNumber = Math.max(highNumber, receivedNumber);
P(s);
boolean decideToDefer = requesting && (number < receivedNumber
|| (number == receivedNumber && id < receivedID));
if (decideToDefer) deferred[receivedID] = true;
else send(replyChannel[receivedID], id);
V(s);
}
}

private void handleReplies() {


while (true) {
int receivedID = receiveInt(repliesToMe);
replyCount++;
if (replyCount == numNodes - 1) V(wakeUp);
}
}
}

class DistributedMutualExclusion extends MyObject {

public static void main(String[] args) {

// parse command line options, if any, to override defaults


GetOpt go = new GetOpt(args, "Un:R:");
String usage = "Usage: -n numNodes -R runTime"
+ " napOutsideCS[i] napInsideCS[i] i=0,1,...";
go.optErr = true;
int ch = -1;
int numNodes = 5;
int runTime = 60; // seconds
while ((ch = go.getopt()) != go.optEOF) {
if ((char)ch == 'U') {
System.out.println(usage); System.exit(0);
}
else if ((char)ch == 'n')
numNodes = go.processArg(go.optArgGet(), numNodes);
else if ((char)ch == 'R')
runTime = go.processArg(go.optArgGet(), runTime);
else {
System.err.println(usage); System.exit(1);
}
}
System.out.println("DistributedMutualExclusion: numNodes="
+ numNodes + ", runTime=" + runTime);

// process non-option command line arguments


int[] napOutsideCS = new int[numNodes];
int[] napInsideCS = new int[numNodes];
int argNum = go.optIndexGet();
for (int i = 0; i < numNodes; i++) {
napOutsideCS[i] = go.tryArg(argNum++, 8);
napInsideCS[i] = go.tryArg(argNum++, 2);
}
// create communication channels
MessagePassing[] requestChannel = null, replyChannel = null,
requestChannelS = null, requestChannelR = null,
replyChannelS = null, replyChannelR = null;
requestChannel = new MessagePassing[numNodes];
replyChannel = new MessagePassing[numNodes];
requestChannelS = new MessagePassing[numNodes];
replyChannelS = new MessagePassing[numNodes];
requestChannelR = new MessagePassing[numNodes];
replyChannelR = new MessagePassing[numNodes];
for (int i = 0; i < numNodes; i++) {
requestChannel[i] = new AsyncMessagePassing();
replyChannel[i] = new AsyncMessagePassing();
requestChannelS[i] = new MessagePassingSendOnly(requestChannel[i]);
replyChannelS[i] = new MessagePassingSendOnly(replyChannel[i]);
requestChannelR[i] = new
MessagePassingReceiveOnly(requestChannel[i]);
replyChannelR[i] = new MessagePassingReceiveOnly(replyChannel[i]);
}

// create the Nodes (they start their own threads)


for (int i = 0; i < numNodes; i++)
new Node("Node", i, numNodes,
napOutsideCS[i]*1000, napInsideCS[i]*1000,
requestChannelS, replyChannelS,
requestChannelR[i], replyChannelR[i]);
System.out.println("All Nodes created");

// let the Nodes run for a while


nap(runTime*1000);
System.out.println("age()=" + age()
+ ", time to stop the threads and exit");
System.exit(0);
}
}
Output:
D:\Prakash\Java\RND\Advanced>javac dimu.java

D:\ Prakash\Java\RND\Advanced >java DistributedMutualExclusion -R20


DistributedMutualExclusion: numNodes=5, runTime=20
Node 0 is alive, napOutsideCS=8000, napInsideCS=2000
Node 1 is alive, napOutsideCS=8000, napInsideCS=2000
Node 2 is alive, napOutsideCS=8000, napInsideCS=2000
Node 3 is alive, napOutsideCS=8000, napInsideCS=2000
Node 4 is alive, napOutsideCS=8000, napInsideCS=2000
age()=170, Node 1 napping outside CS for 2719 ms
age()=170, Node 2 napping outside CS for 279 ms
All Nodes created
age()=170, Node 3 napping outside CS for 2355 ms
age()=220, Node 0 napping outside CS for 2393 ms
age()=220, Node 4 napping outside CS for 8 ms
age()=220, node 4 wants to enter its critical section
age()=330, Node 4 napping inside CS for 911 ms
age()=440, node 2 wants to enter its critical section
age()=1260, node 4 has now left its critical section
age()=1260, Node 4 napping outside CS for 4042 ms
age()=1260, Node 2 napping inside CS for 183 ms
age()=1480, node 2 has now left its critical section
age()=1480, Node 2 napping outside CS for 7335 ms
age()=2530, node 3 wants to enter its critical section
age()=2530, Node 3 napping inside CS for 741 ms
age()=2580, node 0 wants to enter its critical section
age()=2860, node 1 wants to enter its critical section
age()=3300, node 3 has now left its critical section
age()=3300, Node 3 napping outside CS for 6849 ms
age()=3300, Node 0 napping inside CS for 1710 ms
age()=5000, node 0 has now left its critical section
age()=5000, Node 0 napping outside CS for 5253 ms
age()=5000, Node 1 napping inside CS for 1694 ms
age()=5330, node 4 wants to enter its critical section
age()=6700, node 1 has now left its critical section
age()=6700, Node 1 napping outside CS for 3063 ms
age()=6700, Node 4 napping inside CS for 397 ms
age()=7140, node 4 has now left its critical section
age()=7140, Node 4 napping outside CS for 3687 ms
age()=8790, node 2 wants to enter its critical section
age()=8790, Node 2 napping inside CS for 102 ms
age()=8900, node 2 has now left its critical section
age()=8900, Node 2 napping outside CS for 1174 ms
age()=9780, node 1 wants to enter its critical section
age()=9780, Node 1 napping inside CS for 1617 ms
age()=10110, node 2 wants to enter its critical section
age()=10160, node 3 wants to enter its critical section
age()=10270, node 0 wants to enter its critical section
age()=10820, node 4 wants to enter its critical section
age()=11430, node 1 has now left its critical section
age()=11430, Node 1 napping outside CS for 5326 ms
age()=11430, Node 2 napping inside CS for 628 ms
age()=12090, node 2 has now left its critical section
age()=12090, Node 2 napping outside CS for 4970 ms
age()=12090, Node 3 napping inside CS for 545 ms
age()=12630, node 3 has now left its critical section
age()=12630, Node 3 napping outside CS for 7989 ms
age()=12630, Node 0 napping inside CS for 904 ms
age()=13510, node 0 has now left its critical section
age()=13510, Node 0 napping outside CS for 4162 ms
age()=13510, Node 4 napping inside CS for 1440 ms
age()=15000, node 4 has now left its critical section
age()=15000, Node 4 napping outside CS for 2578 ms
age()=16750, node 1 wants to enter its critical section
age()=16750, Node 1 napping inside CS for 123 ms
age()=16860, node 1 has now left its critical section
age()=16860, Node 1 napping outside CS for 3709 ms
age()=17030, node 2 wants to enter its critical section
age()=17030, Node 2 napping inside CS for 97 ms
age()=17140, node 2 has now left its critical section
age()=17140, Node 2 napping outside CS for 7901 ms
age()=17580, node 4 wants to enter its critical section
age()=17580, Node 4 napping inside CS for 1695 ms
age()=17690, node 0 wants to enter its critical section
age()=19280, node 4 has now left its critical section
age()=19280, Node 4 napping outside CS for 3751 ms
age()=19280, Node 0 napping inside CS for 869 ms
age()=20160, node 0 has now left its critical section
age()=20160, Node 0 napping outside CS for 6489 ms
age()=20160, time to stop the threads and exit
... end of example run(s) */

Assignment No.4
//Implement a distributed chat server using TCP Socket.
Solutions
1.Server.java

import java.net.*;
import java.io.*;
public class server{
public static void main(String args[])throws IOException{
ServerSocket s1=null;
try{
s1=new ServerSocket(98);
}catch(Exception e){
System.out.println("Port not found");
e.printStackTrace();
}
Socket c=null;
try{
c=s1.accept();
System.out.println("Connection from"+c);
}catch(Exception e){
System.out.println("not accepted");
e.printStackTrace();
}
PrintWriter out=new PrintWriter(c.getOutputStream(),true);
BufferedReaderin=new BufferedReader(new
InputStreamReader(c.getInputStream()));
String l;
BufferedReader sin=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("I am ready type now");
while((l=sin.readLine())!=null){
out.println(l);
}
out.close();
sin.close();
c.close();
s1.close();
}
}
2.Client.java

import java.net.*;
import java.io.*;
public class client{
public static void main(String args[])throws IOException{
Socket s=null;
BufferedReader b=null;
try{
s=new Socket(InetAddress.getLocalHost(),98);
b=new BufferedReader(new
InputStreamReader(s.getInputStream()));
}catch(Exception e){
System.out.println("I do not host");
e.printStackTrace();
}
String inp;
while((inp=b.readLine())!=null){
System.out.println(inp);
}
b.close();
s.close();
}
}

Running the application


Open two cmd prompt and follow these
1.java Server
2.java client

Output
D:\Prakash\RND\Java\NetWorking\ChatServer>java server
Connection fromSocket[addr=/127.0.0.1,port=1120,localport=98]
I am ready type now
Hello how r u? dude…
D:\Prakash\RND\Java\NetWorking\ChatServer>java client
Hello how r u? dude…

Assignment No.5
// Implement ‘Java RMI’ mechanism for accessing methods of remote
systems.
Solutions
1.CalculatorImpl.java
public class CalculatorImpl
extends
java.rmi.server.UnicastRemoteObject
implements Calculator {
public CalculatorImpl()
throws java.rmi.RemoteException {
super();
}
public long add(long a, long b)
throws java.rmi.RemoteException {
return a + b;
}
public long sub(long a, long b)
throws java.rmi.RemoteException {
return a - b;
}
public long mul(long a, long b)
throws java.rmi.RemoteException {
return a * b;
}
public long div(long a, long b)
throws java.rmi.RemoteException {
return a / b;
}
}

2.Calculator.java
public interface Calculator
extends java.rmi.Remote {
public long add(long a, long b)
throws java.rmi.RemoteException;
public long sub(long a, long b)
throws java.rmi.RemoteException;
public long mul(long a, long b)
throws java.rmi.RemoteException;
public long div(long a, long b)
throws java.rmi.RemoteException;
}

3.CalculatorServer.java

import java.rmi.Naming;
public class CalculatorServer {
public CalculatorServer() {
try {
Calculator c = new CalculatorImpl();
Naming.rebind("rmi://localhost:1099/CalculatorService", c);
} catch (Exception e) {
System.out.println("Trouble: " + e);
}
}
public static void main(String args[]) {
new CalculatorServer();
}
}

4.CalculatorClient.java
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
public class CalculatorClient {
public static void main(String[] args) {
try {
Calculator c = (Calculator)

Naming.lookup("rmi://localhost/CalculatorService");
System.out.println( c.sub(4, 3) );
System.out.println( c.add(4, 5) );
System.out.println( c.mul(3, 6) );
System.out.println( c.div(9, 3) );
}
catch (MalformedURLException murle) {
System.out.println();
System.out.println("MalformedURLException");
System.out.println(murle);
}
catch (RemoteException re) {
System.out.println();
System.out.println("RemoteException");
System.out.println(re);
}
catch (NotBoundException nbe) {
System.out.println();
System.out.println(
"NotBoundException");
System.out.println(nbe);
}
catch ( java.lang.ArithmeticException ae) {
System.out.println();
System.out.println(
"java.lang.ArithmeticException");
System.out.println(ae);
}
}
}
Running The Application:

D:\Prakash\RND\Java\NetWorking\RMI>rmic CalculatorImpl
Now open three cmd prompts and follow these at each.
1. D:\Prakash\RND\Java\NetWorking\RMI>Rmiregistry
2. D:\Prakash\RND\Java\NetWorking\RMI>java CalculatorServer
3. D:\Prakash\RND\Java\NetWorking\RMI>java CalculatorClient

Output:
If all goes well you will see the following output:

1
9
18
3

Assignment No.6

// Implementation of CORBA (Common Object Request Broker


Architecture) mechanism.

Solutions
1.FileInterface.idl
interface FileInterface {
typedef sequence<octet> Data;
Data downloadFile(in string fileName);
};

Now, let's compile the FileInterface.idl and generate server-side skeletons. Using the command:

D:\Prakash\RND\Java\CORBA> idlj -fserver FileInterface.idl

2.FileServant.java
import java.io.*;

public class FileServant extends _FileInterfaceImplBase {


public byte[] downloadFile(String fileName){
File file = new File(fileName);
byte buffer[] = new byte[(int)file.length()];
try {
BufferedInputStream input = new
BufferedInputStream(new FileInputStream(fileName));
input.read(buffer,0,buffer.length);
input.close();
} catch(Exception e) {
System.out.println("FileServant Error: "+e.getMessage());
e.printStackTrace();
}
return(buffer);
}
}

3.FileServer.java
import java.io.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;

public class FileServer {


public static void main(String args[]) {
try{
// create and initialize the ORB
ORB orb = ORB.init(args, null);
// create the servant and register it with the ORB
FileServant fileRef = new FileServant();
orb.connect(fileRef);
// get the root naming context
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
// Bind the object reference in naming
NameComponent nc = new NameComponent("FileTransfer", " ");
NameComponent path[] = {nc};
ncRef.rebind(path, fileRef);
System.out.println("Server started....");
// Wait for invocations from clients
java.lang.Object sync = new java.lang.Object();
synchronized(sync){
sync.wait();
}
} catch(Exception e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace(System.out);
}
}
}

4.FileClient.java
import java.io.*;
import java.util.*;
import org.omg.CosNaming.*;
import org.omg.CORBA.*;

public class FileClient {


public static void main(String argv[]) {
try {
// create and initialize the ORB
ORB orb = ORB.init(argv, null);
// get the root naming context
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
NameComponent nc = new NameComponent("FileTransfer", " ");
// Resolve the object reference in naming
NameComponent path[] = {nc};
FileInterfaceOperations fileRef =
FileInterfaceHelper.narrow(ncRef.resolve(path));

if(argv.length < 1) {
System.out.println("Usage: java FileClient filename");
}

// save the file


File file = new File(argv[0]);
byte data[] = fileRef.downloadFile(argv[0]);
BufferedOutputStream output = new
BufferedOutputStream(new FileOutputStream(argv[0]));
output.write(data, 0, data.length);
output.flush();
output.close();
} catch(Exception e) {
System.out.println("FileClient Error: " + e.getMessage());
e.printStackTrace();
}
}
}
Running the application

1. D:\Prakash\RND\Java\CORBA>tnameserv
2. D:\Prakash\RND\Java\CORBA>java FileServer
3. D:\Prakash\RND\Java\CORBA>idlj -fclient FileInterface.idl
4. D:\Prakash\RND\Java\CORBA>java FileClient hello.txt
Output:
Assignment No.7

//Write a java program for implementing sliding window protocol.

Solutions
1. slic.java
//SLIDING WINDOW PROTOCOL – CLIENT
import java.io.*;
import java.net.*;

public class slic{


public static void main(String args[])throws Exception{
Socket s = new Socket(“local host”,8888);
Buffered Reader from server = new BufferReader(new
InputStreamReader(s.getInputStream()));
DataOutputStream toserver = new
DataOutputStream(s.getOutputStream());
BufferedReader d = new BufferedReader(new
InputStreamReader(System.in));
String dout,din;
System.out.println(“\t”+fromserver.readLine());
System.out.println(“enter quit to exit”);
System.out.println(“enter data for server :”);
While(true)
{
Dout = d.readLine();
If(dout.equals(“quit”))
Break;
toserver.writeBytes(dout+’\n’);
din = fromserver.readLine();
System.out.println(“Server :”+din);
System.out.println(“\nEnter for server :”);
}
}
}

2. slis.java

//SLIDING WINDOW PROTOCOL – SERVER


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

public class slis{


public static void main(String args[])throws Exception{
ServerSocket ss = new ServerSocket(8888);
System.out.println(“\t waiting for client…”);
Socket client = ss.accept();
BufferedReader fromclient = new BufferedReader(new
InputStreamReader(client.getInputStream()));
DataOutputStream toclient = new
DataOutputStream(client.getOutputStream());
BufferedReader d = new BufferedReader(new
InputStreamReader(System.in));
String dout,din;
toclient.writeBytes(“Server ready….”+’\n’);

while(true){
din = fromclient.readLine();
System.out.println(“\n client data:”+din);
System.out.println(“enter for client :”);
dout = d.readLine();
if(dout.equals(“quit”))
break;
toclient.writeBytes(dout+’\n’);
}
}
}
OUTPUT
SAMPLE INPUT OUTPUT:

[csea56host csea56] cc slide07.c


[csea56host csea56]./a.out
window size3

we
2 transferred
ack received
1
1 transferred
ack received
co
2 transferred
ack received
me
3 transferred
ack received
1 transferred
ack received

Assignment No.8
//Implement the concept of file using core java

Solutions
import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Assignment No.9

// Sockets -Basic Client/Server Programming

Solutions
TCP CLIENT
//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(“Sever Says : ” + in.readLine());

userinput = stdin.readLine();

out.println(userinput);

catch(Exception e)

System.exit(0);

TCP SERVER

//tcpserver.java

import java.io.*;

import java.net.*;

public class tcpserver

public static void main(String a[]) throws Exception

System.out.println(“TCP SERVER”);

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);

Sample Output:
CLIENT-SERVER CHATTING USING TCP

*************************************

TCP SERVER

************

Server is ready to connect…

hello

Client Says : hello

How are you

Client Says : I’m doing programs

What programs

Client Says : networking

ok.Go ahead

Client Says : ok.Bye

Bye

TCP CLIENT

***********

Enter the host name to connect

p4-221

Sever Says : hello

hello

Sever Says : how are you

I’m doing programs

Sever Says : What programs


networking

Sever Says : ok.Go ahead

ok.Bye

Assignment No.10

// Thread Programming in Java.

Solutions
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;

RunnableDemo( String name) {


threadName = name;
System.out.println("Creating " + threadName );
}

public void run() {


System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
}catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {


System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {


RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");


R2.start();
}
}
This will produce the following result −

Output
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Assignment No.11

//Implement Network File System (NFS).

LOGIC: Implementation of Clustering using MPI_CH2.

Steps:
Set up Network File System (NFS)
Set up Secure Shell (SSH)
Set up Message Passing Interface (MPI)
Requirement: 2 machine running Linux
Set up Network File System
Consider we have two host machine with ip 10.10.3.4 and 10.10.3.3;

Now I want to make 10.10.3.4 as server and rest as client then to implement NFS file system
between this two follow the following steps:
Step 1: Host with ip 10.10.3.4 edit following file as given
in /etc/exports put entry /home 10.10.3.3(rw, no_root_squash) //we want share
home directory to client.
in /etc/host.deny put entry portmap:ALl
in /etc/hosts.allow put entry
Portmap: 10.10.3.3
lockd: : 10.10.3.3
rquotad : 10.10.3.3
mound: 10.10.3.3
statd : 10.10.3.3
Step 2: Execute following set of command from root on both machine to start the daemons.
rpc.portmap
rpc.mountd, rpc.nfsd
rpc.statd, rpc.lockd
rpc.rquotad

Step 3: Client machine execute following command to mount server directory on client
machine
(If possible make firewall off).
mount 10.10.3.4:/home /mnt/newhome
where 10.10.3.4->server host
/mnt/newhome----directory on client to which server directory /home will be mounted.

OUTPUT:

Test the Working of NFS Setup

We can test our NFS server setup by creating a test file on the server end and check its availability at nfs
clientside or vice-versa.
At the nfsserver end

I have created a new text file named “nfstest.txt’ in that shared directory.

[root@nfsserver ~]# cat > /nfsshare/nfstest.txt

This is a test file to test the working of NFS server setup.

At the nfsclient end

Go to that shared directory in client server and you’ll find that shared file without any manual refresh or
service restart.

[root@nfsclient]# ll /mnt/nfsshare

total 4

-rw-r--r-- 1 root root 61 Sep 21 21:44 nfstest.txt

root@nfsclient ~]# cat /mnt/nfsshare/nfstest.txt

This is a test file to test the working of NFS server setup.


Assignment No.12
//WAP to implement a data server and client by socket programming
using iava

Solution

The server

DateServer.java
package edu.lmu.cs.networking;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
* A TCP server that runs on port 9090. When a client connects, it
* sends the client the current date and time, then closes the
* connection with that client. Arguably just about the simplest
* server you can write.
*/
public class DateServer {

/**
* Runs the server.
*/
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(9090);
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
} finally {
socket.close();
}
}
}
finally {
listener.close();
}
}
}

The client

DateClient.java
package edu.lmu.cs.networking;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import javax.swing.JOptionPane;

/**
* Trivial client for the date server.
*/
public class DateClient {

/**
* Runs the client as an application. First it displays a dialog
* box asking for the IP address or hostname of a host running
* the date server, then connects to it and displays the date that
* it serves.
*/
public static void main(String[] args) throws IOException {
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
Socket s = new Socket(serverAddress, 9090);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
OUTPUT
Assignment No.13
//WAP to implement a two player networked Tic-Toe Game by Socket
Programming using java.

solution
The server

TicTacToeServer.java
package edu.lmu.cs.networking;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* A server for a network multi-player tic tac toe game. Modified and
* extended from the class presented in Deitel and Deitel "Java How to
* Program" book. I made a bunch of enhancements and rewrote large sections
* of the code. The main change is instead of passing *data* between the
* client and server, I made a TTTP (tic tac toe protocol) which is totally
* plain text, so you can test the game with Telnet (always a good idea.)
* The strings that are sent in TTTP are:
*
* Client -> Server Server -> Client
* ---------------- ----------------
* MOVE <n> (0 <= n <= 8) WELCOME <char> (char in {X, O})
* QUIT VALID_MOVE
* OTHER_PLAYER_MOVED <n>
* VICTORY
* DEFEAT
* TIE
* MESSAGE <text>
*
* A second change is that it allows an unlimited number of pairs of
* players to play.
*/
public class TicTacToeServer {

/**
* Runs the application. Pairs up clients that connect.
*/
public static void main(String[] args) throws Exception {
ServerSocket listener = new ServerSocket(8901);
System.out.println("Tic Tac Toe Server is Running");
try {
while (true) {
Game game = new Game();
Game.Player playerX = game.new Player(listener.accept(),
'X');
Game.Player playerO = game.new Player(listener.accept(),
'O');
playerX.setOpponent(playerO);
playerO.setOpponent(playerX);
game.currentPlayer = playerX;
playerX.start();
playerO.start();
}
} finally {
listener.close();
}
}
}

/**
* A two-player game.
*/
class Game {

/**
* A board has nine squares. Each square is either unowned or
* it is owned by a player. So we use a simple array of player
* references. If null, the corresponding square is unowned,
* otherwise the array cell stores a reference to the player that
* owns it.
*/
private Player[] board = {
null, null, null,
null, null, null,
null, null, null};

/**
* The current player.
*/
Player currentPlayer;

/**
* Returns whether the current state of the board is such that one
* of the players is a winner.
*/
public boolean hasWinner() {
return
(board[0] != null && board[0] == board[1] && board[0] ==
board[2])
||(board[3] != null && board[3] == board[4] && board[3] ==
board[5])
||(board[6] != null && board[6] == board[7] && board[6] ==
board[8])
||(board[0] != null && board[0] == board[3] && board[0] ==
board[6])
||(board[1] != null && board[1] == board[4] && board[1] ==
board[7])
||(board[2] != null && board[2] == board[5] && board[2] ==
board[8])
||(board[0] != null && board[0] == board[4] && board[0] ==
board[8])
||(board[2] != null && board[2] == board[4] && board[2] ==
board[6]);
}

/**
* Returns whether there are no more empty squares.
*/
public boolean boardFilledUp() {
for (int i = 0; i < board.length; i++) {
if (board[i] == null) {
return false;
}
}
return true;
}

/**
* Called by the player threads when a player tries to make a
* move. This method checks to see if the move is legal: that
* is, the player requesting the move must be the current player
* and the square in which she is trying to move must not already
* be occupied. If the move is legal the game state is updated
* (the square is set and the next player becomes current) and
* the other player is notified of the move so it can update its
* client.
*/
public synchronized boolean legalMove(int location, Player player) {
if (player == currentPlayer && board[location] == null) {
board[location] = currentPlayer;
currentPlayer = currentPlayer.opponent;
currentPlayer.otherPlayerMoved(location);
return true;
}
return false;
}

/**
* The class for the helper threads in this multithreaded server
* application. A Player is identified by a character mark
* which is either 'X' or 'O'. For communication with the
* client the player has a socket with its input and output
* streams. Since only text is being communicated we use a
* reader and a writer.
*/
class Player extends Thread {
char mark;
Player opponent;
Socket socket;
BufferedReader input;
PrintWriter output;

/**
* Constructs a handler thread for a given socket and mark
* initializes the stream fields, displays the first two
* welcoming messages.
*/
public Player(Socket socket, char mark) {
this.socket = socket;
this.mark = mark;
try {
input = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream(), true);
output.println("WELCOME " + mark);
output.println("MESSAGE Waiting for opponent to connect");
} catch (IOException e) {
System.out.println("Player died: " + e);
}
}

/**
* Accepts notification of who the opponent is.
*/
public void setOpponent(Player opponent) {
this.opponent = opponent;
}

/**
* Handles the otherPlayerMoved message.
*/
public void otherPlayerMoved(int location) {
output.println("OPPONENT_MOVED " + location);
output.println(
hasWinner() ? "DEFEAT" : boardFilledUp() ? "TIE" : "");
}

/**
* The run method of this thread.
*/
public void run() {
try {
// The thread is only started after everyone connects.
output.println("MESSAGE All players connected");

// Tell the first player that it is her turn.


if (mark == 'X') {
output.println("MESSAGE Your move");
}

// Repeatedly get commands from the client and process them.


while (true) {
String command = input.readLine();
if (command.startsWith("MOVE")) {
int location =
Integer.parseInt(command.substring(5));
if (legalMove(location, this)) {
output.println("VALID_MOVE");
output.println(hasWinner() ? "VICTORY"
: boardFilledUp() ? "TIE"
: "");
} else {
output.println("MESSAGE ?");
}
} else if (command.startsWith("QUIT")) {
return;
}
}
} catch (IOException e) {
System.out.println("Player died: " + e);
} finally {
try {socket.close();} catch (IOException e) {}
}
}
}
}

The client

TicTacToeClient.java
package edu.lmu.cs.networking;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
* A client for the TicTacToe game, modified and extended from the
* class presented in Deitel and Deitel "Java How to Program" book.
* I made a bunch of enhancements and rewrote large sections of the
* code. In particular I created the TTTP (Tic Tac Toe Protocol)
* which is entirely text based. Here are the strings that are sent:
*
* Client -> Server Server -> Client
* ---------------- ----------------
* MOVE <n> (0 <= n <= 8) WELCOME <char> (char in {X, O})
* QUIT VALID_MOVE
* OTHER_PLAYER_MOVED <n>
* VICTORY
* DEFEAT
* TIE
* MESSAGE <text>
*
*/
public class TicTacToeClient {

private JFrame frame = new JFrame("Tic Tac Toe");


private JLabel messageLabel = new JLabel("");
private ImageIcon icon;
private ImageIcon opponentIcon;

private Square[] board = new Square[9];


private Square currentSquare;

private static int PORT = 8901;


private Socket socket;
private BufferedReader in;
private PrintWriter out;

/**
* Constructs the client by connecting to a server, laying out the
* GUI and registering GUI listeners.
*/
public TicTacToeClient(String serverAddress) throws Exception {

// Setup networking
socket = new Socket(serverAddress, PORT);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);

// Layout GUI
messageLabel.setBackground(Color.lightGray);
frame.getContentPane().add(messageLabel, "South");

JPanel boardPanel = new JPanel();


boardPanel.setBackground(Color.black);
boardPanel.setLayout(new GridLayout(3, 3, 2, 2));
for (int i = 0; i < board.length; i++) {
final int j = i;
board[i] = new Square();
board[i].addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
currentSquare = board[j];
out.println("MOVE " + j);}});
boardPanel.add(board[i]);
}
frame.getContentPane().add(boardPanel, "Center");
}

/**
* The main thread of the client will listen for messages
* from the server. The first message will be a "WELCOME"
* message in which we receive our mark. Then we go into a
* loop listening for "VALID_MOVE", "OPPONENT_MOVED", "VICTORY",
* "DEFEAT", "TIE", "OPPONENT_QUIT or "MESSAGE" messages,
* and handling each message appropriately. The "VICTORY",
* "DEFEAT" and "TIE" ask the user whether or not to play
* another game. If the answer is no, the loop is exited and
* the server is sent a "QUIT" message. If an OPPONENT_QUIT
* message is recevied then the loop will exit and the server
* will be sent a "QUIT" message also.
*/
public void play() throws Exception {
String response;
try {
response = in.readLine();
if (response.startsWith("WELCOME")) {
char mark = response.charAt(8);
icon = new ImageIcon(mark == 'X' ? "x.gif" : "o.gif");
opponentIcon = new ImageIcon(mark == 'X' ? "o.gif" :
"x.gif");
frame.setTitle("Tic Tac Toe - Player " + mark);
}
while (true) {
response = in.readLine();
if (response.startsWith("VALID_MOVE")) {
messageLabel.setText("Valid move, please wait");
currentSquare.setIcon(icon);
currentSquare.repaint();
} else if (response.startsWith("OPPONENT_MOVED")) {
int loc = Integer.parseInt(response.substring(15));
board[loc].setIcon(opponentIcon);
board[loc].repaint();
messageLabel.setText("Opponent moved, your turn");
} else if (response.startsWith("VICTORY")) {
messageLabel.setText("You win");
break;
} else if (response.startsWith("DEFEAT")) {
messageLabel.setText("You lose");
break;
} else if (response.startsWith("TIE")) {
messageLabel.setText("You tied");
break;
} else if (response.startsWith("MESSAGE")) {
messageLabel.setText(response.substring(8));
}
}
out.println("QUIT");
}
finally {
socket.close();
}
}

private boolean wantsToPlayAgain() {


int response = JOptionPane.showConfirmDialog(frame,
"Want to play again?",
"Tic Tac Toe is Fun Fun Fun",
JOptionPane.YES_NO_OPTION);
frame.dispose();
return response == JOptionPane.YES_OPTION;
}

/**
* Graphical square in the client window. Each square is
* a white panel containing. A client calls setIcon() to fill
* it with an Icon, presumably an X or O.
*/
static class Square extends JPanel {
JLabel label = new JLabel((Icon)null);

public Square() {
setBackground(Color.white);
add(label);
}

public void setIcon(Icon icon) {


label.setIcon(icon);
}
}

/**
* Runs the client as an application.
*/
public static void main(String[] args) throws Exception {
while (true) {
String serverAddress = (args.length == 0) ? "localhost" :
args[1];
TicTacToeClient client = new TicTacToeClient(serverAddress);
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setSize(240, 160);
client.frame.setVisible(true);
client.frame.setResizable(false);
client.play();
if (!client.wantsToPlayAgain()) {
break;
}
}
}
}
Assignment No.14
//WAP to implement a multiuser chat application by Socket Programming
using java

solution

The server

ChatServer.java
package edu.lmu.cs.networking;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;

/**
* A multithreaded chat room server. When a client connects the
* server requests a screen name by sending the client the
* text "SUBMITNAME", and keeps requesting a name until
* a unique one is received. After a client submits a unique
* name, the server acknowledges with "NAMEACCEPTED". Then
* all messages from that client will be broadcast to all other
* clients that have submitted a unique screen name. The
* broadcast messages are prefixed with "MESSAGE ".
*
* Because this is just a teaching example to illustrate a simple
* chat server, there are a few features that have been left out.
* Two are very useful and belong in production code:
*
* 1. The protocol should be enhanced so that the client can
* send clean disconnect messages to the server.
*
* 2. The server should do some logging.
*/
public class ChatServer {

/**
* The port that the server listens on.
*/
private static final int PORT = 9001;

/**
* The set of all names of clients in the chat room. Maintained
* so that we can check that new clients are not registering name
* already in use.
*/
private static HashSet<String> names = new HashSet<String>();

/**
* The set of all the print writers for all the clients. This
* set is kept so we can easily broadcast messages.
*/
private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();

/**
* The appplication main method, which just listens on a port and
* spawns handler threads.
*/
public static void main(String[] args) throws Exception {
System.out.println("The chat server is running.");
ServerSocket listener = new ServerSocket(PORT);
try {
while (true) {
new Handler(listener.accept()).start();
}
} finally {
listener.close();
}
}

/**
* A handler thread class. Handlers are spawned from the listening
* loop and are responsible for a dealing with a single client
* and broadcasting its messages.
*/
private static class Handler extends Thread {
private String name;
private Socket socket;
private BufferedReader in;
private PrintWriter out;

/**
* Constructs a handler thread, squirreling away the socket.
* All the interesting work is done in the run method.
*/
public Handler(Socket socket) {
this.socket = socket;
}

/**
* Services this thread's client by repeatedly requesting a
* screen name until a unique one has been submitted, then
* acknowledges the name and registers the output stream for
* the client in a global set, then repeatedly gets inputs and
* broadcasts them.
*/
public void run() {
try {

// Create character streams for the socket.


in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);

// Request a name from this client. Keep requesting until


// a name is submitted that is not already used. Note that
// checking for the existence of a name and adding the name
// must be done while locking the set of names.
while (true) {
out.println("SUBMITNAME");
name = in.readLine();
if (name == null) {
return;
}
synchronized (names) {
if (!names.contains(name)) {
names.add(name);
break;
}
}
}

// Now that a successful name has been chosen, add the


// socket's print writer to the set of all writers so
// this client can receive broadcast messages.
out.println("NAMEACCEPTED");
writers.add(out);

// Accept messages from this client and broadcast them.


// Ignore other clients that cannot be broadcasted to.
while (true) {
String input = in.readLine();
if (input == null) {
return;
}
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + ": " + input);
}
}
} catch (IOException e) {
System.out.println(e);
} finally {
// This client is going down! Remove its name and its print
// writer from the sets, and close its socket.
if (name != null) {
names.remove(name);
}
if (out != null) {
writers.remove(out);
}
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}

The client

ChatClient.java
package edu.lmu.cs.networking;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
* A simple Swing-based client for the chat server. Graphically
* it is a frame with a text field for entering messages and a
* textarea to see the whole dialog.
*
* The client follows the Chat Protocol which is as follows.
* When the server sends "SUBMITNAME" the client replies with the
* desired screen name. The server will keep sending "SUBMITNAME"
* requests as long as the client submits screen names that are
* already in use. When the server sends a line beginning
* with "NAMEACCEPTED" the client is now allowed to start
* sending the server arbitrary strings to be broadcast to all
* chatters connected to the server. When the server sends a
* line beginning with "MESSAGE " then all characters following
* this string should be displayed in its message area.
*/
public class ChatClient {

BufferedReader in;
PrintWriter out;
JFrame frame = new JFrame("Chatter");
JTextField textField = new JTextField(40);
JTextArea messageArea = new JTextArea(8, 40);

/**
* Constructs the client by laying out the GUI and registering a
* listener with the textfield so that pressing Return in the
* listener sends the textfield contents to the server. Note
* however that the textfield is initially NOT editable, and
* only becomes editable AFTER the client receives the NAMEACCEPTED
* message from the server.
*/
public ChatClient() {

// Layout GUI
textField.setEditable(false);
messageArea.setEditable(false);
frame.getContentPane().add(textField, "North");
frame.getContentPane().add(new JScrollPane(messageArea), "Center");
frame.pack();

// Add Listeners
textField.addActionListener(new ActionListener() {
/**
* Responds to pressing the enter key in the textfield by sending
* the contents of the text field to the server. Then clear
* the text area in preparation for the next message.
*/
public void actionPerformed(ActionEvent e) {
out.println(textField.getText());
textField.setText("");
}
});
}

/**
* Prompt for and return the address of the server.
*/
private String getServerAddress() {
return JOptionPane.showInputDialog(
frame,
"Enter IP Address of the Server:",
"Welcome to the Chatter",
JOptionPane.QUESTION_MESSAGE);
}

/**
* Prompt for and return the desired screen name.
*/
private String getName() {
return JOptionPane.showInputDialog(
frame,
"Choose a screen name:",
"Screen name selection",
JOptionPane.PLAIN_MESSAGE);
}

/**
* Connects to the server then enters the processing loop.
*/
private void run() throws IOException {

// Make connection and initialize streams


String serverAddress = getServerAddress();
Socket socket = new Socket(serverAddress, 9001);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);

// Process all messages from server, according to the protocol.


while (true) {
String line = in.readLine();
if (line.startsWith("SUBMITNAME")) {
out.println(getName());
} else if (line.startsWith("NAMEACCEPTED")) {
textField.setEditable(true);
} else if (line.startsWith("MESSAGE")) {
messageArea.append(line.substring(8) + "\n");
}
}
}

/**
* Runs the client as an application with a closeable frame.
*/
public static void main(String[] args) throws Exception {
ChatClient client = new ChatClient();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setVisible(true);
client.run();
}
}
OUTPUT
Assignment No.15
//WAP to implement RPC mechanism for file transfer across a network
using java

client.java
import java.io.*;
import java.net.*;
class client{
public static void main(String args[]){
try{
Socket sock=new Socket (args[0],8081);
FileInputStream is=new FileInputStream("client.class");
OutputStream os=sock.getOutput
Stream();
int ch=0;
ch=is.read();
do{
os.write(ch);
ch=is.read();
}while(ch!=
-
1);
os.flush();
os.close();
sock.close();
}
catch(Exception e){System.out.println(e);}
}
}
server.java
import java.io.*;
import java.net.*;
class server {
public static voi
d main(String args[]){
new server().go();
}
public void go(){
while(true){
try{
ServerSocket server=new ServerSocket(8081);
Socket socket=server.accept();
new Thread(new thread(socket)).start();
}
catch(Exception e){
}
}
Distributed Systems
Lab
oratory
}
class thread implements
Runnable{
Socket s;
thread(Socket s){
this.s=s;
}
public void run(){
try{
InputStream is=s.getInputStream();
FileOutputStream out =new FileOutputStream(new
File("clientcopy.class"));
int ch=0;
ch=is.read();
do{
out.write(ch);
ch=is.read();
}while(ch!=
-
1);
out.flush();
System.out.println("File (client.class) Copied to server as
(clientcopy.class)");
out.close();
s.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
}

You might also like