Professional Documents
Culture Documents
java
This program implements Maekawa's voting algorithm for mutual exclusion
as described in R. Chow et al, "Distributed Operating Systems &
Algorithms".
import daj.*;
import Prog;
import java.lang.Math;
/* construct creates the nodes and the links between them randomly */
public void construct() {
int i, j;
setChannelWidth(2);
try
{
serverSocket.close();
}
catch(Exception e1)
{
}
}
}
class clientThread extends Thread
{
DataInputStream is = null;
String line;
String destClient="";
String name;
PrintStream os = null;
Socket clientSocket = null;
String clientIdentity;
Server ser;
public clientThread(Server ser,Socket clientSocket)
{
this.clientSocket=clientSocket;
this.ser=ser;
}
public void run()
{
try
{
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
os.println("Enter your name.");
name = is.readLine();
clientIdentity=name;
os.println("Welcome "+name+" to this 2 Phase Application.\nYou will receive a vote Request
now...");
os.println("VOTE_REQUEST\nPlease enter COMMIT or ABORT to proceed : ");
for(int i=0; i<(ser.t).size(); i++)
{
if((ser.t).get(i)!=this)
{
((ser.t).get(i)).os.println("---A new user "+name+" entered the Appilcation---");
}
}
while (true)
{
line = is.readLine();
if(line.equalsIgnoreCase("ABORT"))
{
System.out.println("\nFrom '"+clientIdentity+"' : ABORT\n\nSince aborted we will not wait
for inputs from other clients.");
System.out.println("\nAborted....");
for(int i=0; i<(ser.t).size(); i++)
{
((ser.t).get(i)).os.println("GLOBAL_ABORT");
((ser.t).get(i)).os.close();
((ser.t).get(i)).is.close();
}
break;
}
if(line.equalsIgnoreCase("COMMIT"))
{
System.out.println("\nFrom '"+clientIdentity+"' : COMMIT");
if((ser.t).contains(this))
{
(ser.data).set((ser.t).indexOf(this), "COMMIT");
for(int j=0;j<(ser.data).size();j++)
{
if(!(((ser.data).get(j)).equalsIgnoreCase("NOT_SENT")))
{
ser.inputFromAll=true;
continue;
}
else
{
ser.inputFromAll=false;
System.out.println("\nWaiting for inputs from other clients.");
break;
}
}
if(ser.inputFromAll)
{
System.out.println("\n\nCommited....");
for(int i=0; i<(ser.t).size(); i++)
{
((ser.t).get(i)).os.println("GLOBAL_COMMIT");
((ser.t).get(i)).os.close();
((ser.t).get(i)).is.close();
}
break;
}
}//if t.contains
}//commit
}//while
ser.closed=true;
clientSocket.close();
}
catch(IOException e)
{
};}}
2. Client.java:
import java.io.*;
import java.net.*;
public class Client implements Runnable
{
static Socket clientSocket = null;
static PrintStream os = null;
static DataInputStream is = null;
static BufferedReader inputLine = null;
static boolean closed = false;
public static void main(String[] args)
{
int port_number=1111;
String host="localhost";
try
{
clientSocket = new Socket(host, port_number);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
}
catch (Exception e)
{
System.out.println("Exception occurred : "+e.getMessage());
}
if (clientSocket != null && os != null && is != null)
{
try
{
new Thread(new Client()).start();
while (!closed)
{
os.println(inputLine.readLine());
}
os.close();
is.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("IOException: " + e);
}
}
} public void run()
{
String responseLine;
try
{
while ((responseLine = is.readLine()) != null)
{
System.out.println("\n"+responseLine);
if (responseLine.equalsIgnoreCase("GLOBAL_COMMIT")==true ||
responseLine.equalsIgnoreCase("GLOBAL_ABORT")==true )
{
break;
}
}
closed=true;
}
catch (IOException e)
{
System.err.println("IOException: " + e);
}}}
QUESTION NO N0 3
import
java.io.*;
import java.util.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RingElection {
if(curPid != coord) {
while(c_alive != 0) {
cdSend = new DatagramPacket(cdsMsg, cdsMsg.length,
InetAddress.getByName(cdAddress), cdPort);
socket1.send(cdSend);
try {
socket1.setSoTimeout(3000);
socket1.receive(cdRecv);
}
catch(Exception e) {
c_alive = 0; elNum = 0;
}
}
}
else if(curPid == coord) {
System.out.println("I'm the co-ordinator");
while(curPid == coord) {
socket1.receive(cdRecv);
cdSend2 = new DatagramPacket(cdsMsg, cdsMsg.length,
cdRecv.getAddress(), cdRecv.getPort());
socket1.send(cdSend2);
}
}
}
}
catch(Exception e) {
}
}
class CRThread implements Runnable {
int temp;
socket4.receive(recvPacket);
String str = new String(recvPacket.getData());
temp = Character.getNumericValue(str.charAt(0));
if(temp > coord) {
coord = temp;
cdAddress = sAddress[coord-1];
cdPort = sPorts[coord-1];
System.out.println("Node " + coord + " restarted");
while(!queue.isEmpty())
queue.remove();
c_alive = 0;
elNum = 0;
}
}
}
catch(Exception e) {
System.out.println("ERROR in Server Check Receive Thread");
}
}
}
class CSThread implements Runnable {
socket2.receive(recvPacket);
DatagramPacket sendPacket = new DatagramPacket(kMsg,
kMsg.length, recvPacket.getAddress(), recvPacket.getPort());
String str = new String(recvPacket.getData());
str = str.trim();
String subStr = str.substring(0, 8);
int len = str.length();
System.out.println("Received : " + str);
if(subStr.equals("ELECTION")) {
socket2.send(sendPacket);
if(Character.getNumericValue(str.charAt(9)) != curPid) {
str = str + Integer.toString(curPid);
queue.add(str);
}
else {
if(subStr.equals("COORDNTR")) {
socket2.send(sendPacket);
if(Character.getNumericValue(str.charAt(9)) != curPid) {
coord = Character.getNumericValue(str.charAt(9));
cdPort = sPorts[coord-1];
cdAddress = address[coord-1];
System.out.println("Co-Ordinator: Node " + coord);
c_alive = 1; elNum = 1;
queue.add(str);
}
else {
coord = curPid;
cdPort = port1;
cdAddress = address1;
c_alive = 1; elNum = 1;
System.out.println("I'm the co-ordinator");
}
}
}
catch(Exception e) {
}
}
}
catch(Exception e) {
System.out.println("ERROR in thread 1" + e);
}
}
}
class SendThread implements Runnable {
public void run() {
try {
while(true) {
int live_node = 0;
byte[] msg = new byte[1024];
Thread.currentThread().sleep(3000);
System.out.print("");
if(elNum == 0) {
elNum = 1;
String str = elMsg + Integer.toString(curPid);
byte[] elByte = str.getBytes();
for(int i = 0; i < n-1; i++) {
DatagramPacket recvPacket = new DatagramPacket(msg,
msg.length);
DatagramPacket sendPacket = new DatagramPacket(elByte,
elByte.length, InetAddress.getByName(address[i]), port[i]);
socket3.send(sendPacket);
try {
live_node = (curPid % n) + i + 1;
socket3.setSoTimeout(3000);
socket3.receive(recvPacket);
String okAck = new String(recvPacket.getData());
System.out.println("Sent : " + str);
break;
}
catch(Exception e) {
}
}
}
while((!queue.isEmpty())) {
try {
live_node = (curPid % n) + i + 1;
socket3.setSoTimeout(1000);
socket3.receive(recvPacket);
String okAck = new String(recvPacket.getData());
System.out.println("Sent : " + msStr);
break;
}
catch(Exception e) {
}
}
}
}
}
catch(Exception e) {
System.out.println("ERROR" + e);
}
}
}
class Communication extends JFrame implements ActionListener {
JTextArea taMessages;
JTextField tfInput;
JButton btnSend,btnExit;
super(uname);
buildInterface();
new MessagesThread().start();
}
String str;
if((curPid == coord) && (queue.isEmpty())) {
for(int i = 0; i < n; i++) {
str = tfInput.getText(); //send
byte[] msg = str.getBytes();
if(i != curPid-1) {
try {
DatagramPacket sendPacket = new DatagramPacket(msg,
msg.length, InetAddress.getByName(sAddress[i]), mPorts[i]);
socket6.send(sendPacket);
}
catch(Exception e) {
}
}
str = "";
}
}
}
}
try {
while(true) {
if(curPid != coord) {
byte[] msg = new byte[1024];
DatagramPacket recvPacket = new DatagramPacket(msg,
msg.length);
socket6.receive(recvPacket);
String str = new String(recvPacket.getData());
str = str.trim();
if(str.equals(prev))
str = "Receiving same message";
else
prev = str;
str = "<Co-ordinator>: " + str;
taMessages.append(str + "\n");//receive
str = "";
}
}
}
catch(Exception ex) {
}
}
}
}
public static void main(String args[]) throws Exception {
RingElection obj = new RingElection();
}
}
/**
* @author Benjamin Hill
*/
public class ClockSync {
/**
* The reason for this to exist. Use instead of
System.currentTimeMillis()
*/
public static long getAdjustedTime() {
return System.currentTimeMillis() + timerOffset;
}
/**
* Sends out a timestamped multicast "ping"
*/
final class BroadcastTask extends TimerTask {
@Override
public void run() {
ClockSync.this.bout.putShort(PACKET_CLASS);
ClockSync.this.bout.putInt(ClockSync.this.myId);
ClockSync.this.bout.putLong(ClockSync.getAdjustedTime());
final DatagramPacket dp = new
DatagramPacket(ClockSync.this.bout.array(), ClockSync.this.bout.position(),
ClockSync.this.group, UPNP_MULTI_PORT);
try {
ClockSync.this.ms.send(dp);
ClockSync.this.bout.clear();
} catch (final IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
logger.finer("Sent ClockSync ping");
}
}
/**
* Blocking thread for getting timer packets
*/
final class ReceiveThread implements Runnable {
boolean running = false;
@Override
public void run() {
this.running = true;
while (this.running) {
try {
ClockSync.this.bin.clear();
final DatagramPacket dp = new
DatagramPacket(ClockSync.this.bin.array(), ClockSync.this.bin.capacity());
logger.finest("Waiting for next packet");
ClockSync.this.ms.receive(dp); // BLOCK HERE
ClockSync.this.bin.rewind();
final long now = ClockSync.getAdjustedTime();
final short pclass = ClockSync.this.bin.getShort();
if (PACKET_CLASS != pclass) {
logger.finest("Random packet, skipping");
continue;
}
final int id = ClockSync.this.bin.getInt();
if (id == ClockSync.this.myId) {
logger.finest("My own packet, skipping");
continue;
}
final long ts = ClockSync.this.bin.getLong();
if (now >= ts) {
logger.finest("Other peer is behind me, skipping");
continue;
}
logger.log(Level.FINER, "Got Relevent Packet:{0} {1} {2}", new
Object[]{pclass, id, ts});
final long ahead = ts - now;
timerOffset += (ahead >> 1);
logger.log(Level.INFO, "Other peer is {0} ahead of me, catching
up halfway with a new offset of {1}", new Object[]{ahead, timerOffset});
} catch (final IOException ex) {
logger.severe(ex.getLocalizedMessage());
this.running = false;
}
}
}
}
protected static volatile long timerOffset = 0;
static final Logger logger = Logger.getLogger(ClockSync.class.getName());
final static short PACKET_CLASS = 2700; // random
static final Random r = new Random();
static final String UPNP_ADDRESS = "239.255.255.250";
static final int UPNP_MULTI_PORT = 1900;
final ByteBuffer bin, bout;
final int BUFF_SIZE = Short.SIZE + Integer.SIZE + Long.SIZE; // Packet
class + machine ID + Time
final InetAddress group;
final MulticastSocket ms;
final int myId;
final ReceiveThread rc = new ReceiveThread();
final Thread recThread = new Thread(rc);
final Timer broadTask = new Timer();
public ClockSync() throws IOException {
this.ms = new MulticastSocket(null);
this.group = InetAddress.getByName(UPNP_ADDRESS);
this.ms.setTimeToLive(4);
this.ms.setSoTimeout(0);
this.ms.setLoopbackMode(true);
this.ms.setReuseAddress(true);
if (!this.ms.getReuseAddress()) {
logger.warning("MS Socket can't reuse address");
}
this.ms.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"),
UPNP_MULTI_PORT));
this.ms.joinGroup(this.group);
this.bin = ByteBuffer.allocate(this.BUFF_SIZE);
this.bout = ByteBuffer.allocate(this.BUFF_SIZE);
this.myId = r.nextInt();
}
/**
* Don't forget to run this!
*/
public void startSync() {
this.recThread.start();
this.broadTask.schedule(new BroadcastTask(), 0, 5000);
}
/**
* Don't bother stopping it if you are ok with the overhead, in case new
clients join
*/
public void stopSync() {
this.rc.running = false;
this.broadTask.cancel();
}
@Override
protected void finalize() throws Throwable {
super.finalize();
if (!this.ms.isClosed()) {
if (this.ms.isBound() && !this.ms.isClosed()) {
this.ms.leaveGroup(this.group);
this.ms.close();
}
}
}
}