: 0208-8110
//FTPServer.java
import java.net.*;
import java.io.*;
import java.util.*;
transferfile(Socket soc)
{
try
{
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
System.out.println("FTP Client Connected ...");
start();
}
catch(Exception ex)
{ }
}
String temp;
do
{
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
{
fout.write(ch);
}
}while(ch!=-1);
fout.close();
dout.writeUTF("File Send Successfully");
}
else
{
return;
}
}
catch(Exception ex)
{ }
}
}
}
//FTPClient.java
import java.net.*;
import java.io.*;
4 Distributed Systems Lab
Date: Roll no. : 0208-8110
import java.util.*;
class FTPClient
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket("127.0.0.1",5217);
transferfileClient t=new transferfileClient(soc);
t.displayMenu();
}
}
class transferfileClient
{
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
BufferedReader br;
transferfileClient(Socket soc)
{
try
{
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
br=new BufferedReader(new InputStreamReader(System.in));
}
catch(Exception ex)
{ }
}
String msgFromServer=din.readUTF();
if(msgFromServer.compareTo("File Already Exists")==0)
{
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=br.readLine();
if(Option=="Y")
{
dout.writeUTF("Y");
}
else
{
dout.writeUTF("N");
return;
}
}
System.out.println("Sending File ...");
FileInputStream fin=new FileInputStream(f);
int ch;
do
{
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
}
while(ch!=-1);
fin.close();
System.out.println(din.readUTF());
}
if(f.exists())
{
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=br.readLine();
if(Option=="N")
{
dout.flush();
return;
}
}
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
{
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
{
fout.write(ch);
}
}while(ch!=-1);
fout.close();
System.out.println(din.readUTF());
}
}
{
dout.writeUTF("GET");
ReceiveFile();
}
else
{
dout.writeUTF("DISCONNECT");
System.exit(1);
}
}
}
}
Output:
Server Client
>java FTPServer >java FTPClient
FTP Server Started on Port Number 5217 [ MENU ]
Waiting for Connection ... 1. Send File
FTP Client Connected ... 2. Receive File
Waiting for Connection ... 3. Exit
Waiting for Command ...
SEND Command Receiced ... Enter Choice :1
Waiting for Command ... Enter File Name :FTPClient.java
Disconnect Command Received ... File Already Exists. Want to OverWrite (Y/N) ?
Y
[ MENU ]
1. Send File
2. Receive File
3. Exit
Enter Choice :3
2. Program to implement File Transfer Protocol by providing a GUI for the access of all services
//FtpServer.java
import java.io.*;
import java.net.*;
{
public static void main(String [] args)
{
int i=1;
System.out.println("***************");
System.out.println("**********");
System.out.println("********");
System.out.println("Server Started...");
System.out.println("Waiting for connections...");
System.out.println(" ");
try
{
ServerSocket s = new ServerSocket(100);
for(;;)
{
Socket incoming = s.accept();
System.out.println("New Client Connected with id " + i +" from "+
incoming.getInetAddress().getHostName()+"..." );
Thread t = new ThreadedServer(incoming,i);
i++;
t.start();
}
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}
}
dir.mkdir();
}
else
{ }
File f=new File(dir,fn);
FileOutputStream fos=new FileOutputStream(f);
DataOutputStream dops=new DataOutputStream(fos);
while(done)
{
fc=in.readLine();
if(fc==null)
{
done=false;
}
else
{
dops.writeChars(fc);
// System.out.println(fc);
}
}
fos.close();
}
catch(Exception ecc)
{
System.out.println(ecc.getMessage());
}
}
incoming.close();
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}
//FtpClient.java
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
String fc;
String dirn="c:/client";
JPanel pnl;
JLabel lbltle,lblud;
Font fnt;
JTextField txtfn;
JButton btnu,btnd;
Socket s;
InputStreamReader in;
OutputStream out;
BufferedReader br;
PrintWriter pw;
public FtpClient()
{
super("FTP CLIENT");
pnl=new JPanel(null);
fnt=new Font("Times New Roman",Font.BOLD,25);
lbltle=new JLabel("FTP CLIENT");
lbltle.setFont(fnt);
lbltle.setBounds(225,35,200,30);
pnl.add(lbltle);
lblud=new JLabel("ENTER FILE-NAME :");
lblud.setBounds(100,100,150,35);
pnl.add(lblud);
txtfn=new JTextField();
txtfn.setBounds(300,100,200,25);
pnl.add(txtfn);
btnu=new JButton("UPLOAD");
btnu.setBounds(150,200,120,35);
pnl.add(btnu);
btnd=new JButton("DOWNLOAD");
btnd.setBounds(320,200,120,35);
pnl.add(btnd);
btnu.addActionListener(this);
btnd.addActionListener(this);
getContentPane().add(pnl);
try
{
s=new Socket("localhost",100);
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
pw=new PrintWriter(s.getOutputStream(),true);
out=s.getOutputStream();
}
catch(Exception e)
13 Distributed Systems Lab
Date: Roll no. : 0208-8110
{
System.out.println("ExCEPTION :"+e.getMessage());
}
}
while(done)
{
fc=br.readLine();
if(fc==null)
{
done=false;
}
else
{
dops.writeChars(fc);
//System.out.println(fc);
}
}
fos.close();
}
catch(Exception exx)
{ }
}
}
Output:
Server
>java FtpServer
***************
**********
********
Server Started...
Waiting for connections...
Client
>java FtpClient
import java.rmi.*;
import java.rmi.RemoteException;
RMI Server
// myApplicationServer.java
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.*;
System.err.println("myApplicationClientException:"+error.getMessage());
}
}
}
Output:
Server Client
>javac *.java >java myApplicationClient
>start rmiregistry i am here to serve.
>rmic myApplicationServer
>java myApplicationServer
import java.net.*;
import java.io.*;
{
while (true)
{
String host = buffer.readLine();
if (host.equalsIgnoreCase("exit"))
{
break;
}
System.out.println(lookup(host));
}
}
catch (IOException ex)
{
System.err.println(ex);
}
}
}
private static String lookup(String hostname)
{
InetAddress node;
try
{
node = InetAddress.getByName(hostname);
}
catch (UnknownHostException ex)
{
return "Cannot find host " + hostname;
}
if (isHostname(hostname))
{
System.out.print("Host Address you have requested is : ");
return node.getHostAddress();
}
else
{
System.out.print("Host Name you have requested is : ");
return node.getHostName();
}
}
}
}
Output:
>java NameServer
Enter an IP Address or Computer Name
Enter "exit".
www.cbit.ac.in
Host Address you have requested is : 202.65.147.165
exit
//ChatServer.java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
} catch(NumberFormatException nfe)
{
System.err.println("Usage: java ChatServer [port]");
System.err.println("Where options include:");
System.err.println("\tport- the port on which to listen.");
System.exit(0);
}
try
{
serverSocket = new ServerSocket(port);
while(true)
{
socket = serverSocket.accept();
ChatHandler handler = new ChatHandler(socket);
handler.start();
}
} catch(IOException ioe)
{
ioe.printStackTrace();
} finally
{
try {
serverSocket.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
//ChatHandler.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Vector;
while(!(line = in.readLine()).equalsIgnoreCase("/quit"))
{
for(int i = 0; i < handlers.size(); i++)
{
synchronized(handlers)
{
ChatHandler handler = (ChatHandler)handlers.elementAt(i);
handler.out.println( ":" +line + "\r");
handler.out.flush();
}
}
}
} catch(IOException ioe)
{
ioe.printStackTrace();
} finally
{
try
{
in.close();
out.close();
socket.close();
} catch(IOException ioe)
23 Distributed Systems Lab
Date: Roll no. : 0208-8110
{ }
finally
{
synchronized(handlers)
{
handlers.removeElement(this);
}
}
}
}
}
Output:
Server
>java ChatServer.java
Client
Client 1 Client 2
B.E 4/4 C-2 CHAT ROOM B.E 4/4 C-2 CHAT ROOM
The number of users connected are : 1 The number of users connected are : 2
B.E 4/4 C-2 CHAT ROOM :Hello
The number of users connected are : 2 Hi
Hello :Hi
:Hello
:Hi
//ChatServer.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
{
System.out.println(" Chat Server 0.1 starting...");
ChatServer w = new ChatServer( );
w.runServer( ); // should never return.
System.out.println("**ERROR* Chat Server 0.1 quitting");
}
/** Construct (and run!) a Chat Service */
ChatServer( )
{
clients = new ArrayList( );
try
{
servSock = new ServerSocket(PORTNUM);
System.out.println("Chat Server Listening on port " + PORTNUM);
}catch(IOException e)
{
log("IO Exception in ChatServer.<init>");
System.exit(0);
}
}
catch(IOException e)
{
log("IO Exception in runServer: " + e);
System.exit(0);
}
}
{
char c = line.charAt(0);
line = line.substring(1);
switch (c)
{
case 'l': //login
login = line;
broadcast(CHATMASTER_ID, login +" joins
us, for a total of " + clients.size( ) + " users");
break;
case 'm': //to display message
if (login == null)
{
send(CHATMASTER_ID, "please
login first");
continue;
}
int where = line.indexOf(':');
if(where>1)
{
String recip =
line.substring(0, where);
String mesg =
line.substring(where+1);
log("MESG: " + login + "-->" + recip +
": "+mesg);
ChatHandler cl = lookup(recip);
if (cl == null)
psend(CHATMASTER_ID,
recip + " not loggedin.");
else
cl.psend(login, mesg);
}
else
{
String mesg = line;
broadcast(login,mesg);
}
break;
case 'q': //quit the server
broadcast(CHATMASTER_ID, "Goodbye to
"+login);
close( );
return; // END OF THIS CHATHANDLER
default: log("Unknown cmd " + c + " from " +
28 Distributed Systems Lab
Date: Roll no. : 0208-8110
clientSock.close( );
clientSock = null;
}catch(IOException e)
{
log("Failure during close to " + clientIP);
}
}
}
return null;
}
//ChatRoom.java
import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
String name;
ChatRoom()
{
cp = new JFrame(TITLE);
cp.setLayout(new BorderLayout( ));
port = PORTNUM;
ta = new TextArea("",20, 80,0);
ta.setEditable(false); // readonly
ta.setFont(new Font("Monospaced", Font.PLAIN, 11));
cp.add(BorderLayout.NORTH, ta);
Panel p = new Panel( );
Button b;
// The login button
p.add(lib = new JButton("Login"));
lib.setEnabled(true);
lib.requestFocus( );
lib.addActionListener(this);
// The logout button
p.add(lob = new JButton("Logout"));
lob.setEnabled(false);
lob.addActionListener(this);
p.add(new Label("Message here:"));
tf = new JTextField(40);
tf.addActionListener(this);
p.add(tf);
p.add(send = new JButton("Send"));
send.setEnabled(false);
send.addActionListener(this);
//warna = new TextArea("",2, 80,0);
// warna.setEditable(false); // readonly
// warna.setFont(new Font("Monospaced", Font.PLAIN, 11));
// cp.add(BorderLayout.CENTRE,warna);
// //p.add(warna);
cp.add(BorderLayout.SOUTH, p);
cp.pack( );
// After packing the Frame, centre it on the screen.
Dimension us = cp.getSize( ),them = Toolkit.getDefaultToolkit().getScreenSize( );
int newX = (them.width - us.width) / 2;
int newY = (them.height- us.height)/ 2;
cp.setLocation(newX, newY);
cp.setVisible(true);
send.setEnabled(false);
d= new dispclass();
//c=new cheksend();
32 Distributed Systems Lab
Date: Roll no. : 0208-8110
cp.addWindowListener(new WindowAdapter( )
{
public void windowClosing(WindowEvent e)
{
// If we do setVisible and dispose, then the Close completes
ChatRoom.this.cp.setVisible(false);
ChatRoom.this.cp.dispose( );
d.t.stop();
logout( );
}
});
}
{
String s=ae.getActionCommand();
if("Login".equals(s))
{
login1( );
if(loggedIn)
{
lib.setEnabled(false);
lob.setEnabled(true);
tf.requestFocus( ); // set keyboard focus in rightplace!
}
//send.setEnabled(true);
}
if("Logout".equals(s))
{
logout( );
lib.setEnabled(true);
lob.setEnabled(false);
//send.setEnabled(false);
lib.requestFocus( );
}
if("Send".equals(s))
{
String line;
if(tf.getText().length()!=0 )
if(loggedIn )
{
pw.println("m"+tf.getText());
tf.setText("");
}
else
{
name=tf.getText();
try
{
//System.out.println(InetAddress.getLocalHost());
sock = new Socket(ip,port);
is = new BufferedReader(new
InputStreamReader(sock.getInputStream( )));
pw = new PrintWriter(sock.getOutputStream( ),
true);
loggedIn = true;
}
catch(IOException e)
{
35 Distributed Systems Lab
Date: Roll no. : 0208-8110
Output:
Server
>java ChatServer
Chat Server 0.1 starting...
Chat Server Listening on port 7777
Accepted from 127.0.0.1
Broadcasting ChatMaster: Rahul joins us, for a total of 1 users
Broadcasting Rahul: Hello C2
Broadcasting ChatMaster: Goodbye to Rahul
Rahul: All Done
ChatMaster: Im so lonely I could cry...
Client
>java ChatRoom 127.0.0.1
import java.sql.*;
import javax.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.*;
import oracle.jdbc.pool.OracleDataSource;
import oracle.jdbc.xa.OracleXid;
import oracle.jdbc.xa.OracleXAException;
import oracle.jdbc.xa.client.*;
import javax.transaction.xa.*;
class TwoPC
{
public static void main (String args []) throws SQLException
{
try
{
String URL1 = "jdbc:oracle:thin:@172.16.2.56:1521:master";
String URL2 = "jdbc:oracle:thin:@172.16.2.56:1521:slave";
DriverManager.registerDriver(new OracleDriver());
// You can put a database name after the @ sign in the connection URL
Connection conna =DriverManager.getConnection (URL1, "system", "cbit");
}
try
{
// Create a test table
stmta.execute ("create table my_table (col1 int)");
}
catch (SQLException e)
{
// Ignore an error here too
}
try
{
// Drop the test table
stmtb.execute ("drop table my_tab");
}
catch (SQLException e)
{
// Ignore an error here
}
try
{
// Create a test table
stmtb.execute ("create table my_tab (col1 char(30))");
}
catch (SQLException e)
{
// Ignore an error here too
}
// Create a XADataSource instance
OracleXADataSource oxds1 = new OracleXADataSource();
oxds1.setURL("jdbc:oracle:thin:@172.16.2.56:1521:master");
oxds1.setUser("system");
oxds1.setPassword("cbit");
OracleXADataSource oxds2 = new OracleXADataSource();
oxds2.setURL("jdbc:oracle:thin:@172.16.2.56:1521:slave");
oxds2.setUser("system");
oxds2.setPassword("cbit");
// Close connections
conn1.close();
conn1 = null;
conn2.close();
conn2 = null;
pc1.close();
pc1 = null;
pc2.close();
pc2 = null;
ResultSet rset = stmta.executeQuery ("select col1 from my_table");
while (rset.next())
System.out.println("Col1 is " + rset.getInt(1));
rset.close();
rset = null;
rset = stmtb.executeQuery ("select col1 from my_tab");
while (rset.next())
System.out.println("Col1 is " + rset.getString(1));
rset.close();
rset = null;
stmta.close();
stmta = null;
stmtb.close();
stmtb = null;
conna.close();
conna = null;
connb.close();
connb = null;
} catch (SQLException sqe)
{
sqe.printStackTrace();
} catch (XAException xae)
{
if (xae instanceof OracleXAException)
{
System.out.println("XA Error is " +
((OracleXAException)xae).getXAError());
System.out.println("SQL Error is " +
((OracleXAException)xae).getOracleError());
}
}
}
{
byte[] gid = new byte[1]; gid[0]= (byte) 9;
byte[] bid = new byte[1]; bid[0]= (byte) bids;
byte[] gtrid = new byte[64];
byte[] bqual = new byte[64];
System.arraycopy (gid, 0, gtrid, 0, 1);
System.arraycopy (bid, 0, bqual, 0, 1);
Xid xid = new OracleXid(0x1234, gtrid, bqual);
return xid;
}
Output:
>java TwoPC
No. of Rows affected: 1
No. of Rows affected: 1
Return value of prepare1 is 0
Return value of prepare2 is 0
do_commit is true
Is oxar1 same as oxar2 ? false
Col1 is 4321
Col1 is test
The network file system (NFS), designed by Sun Microsystems, Inc. in the 1980s, is a client/service
application that provides shared file storage for clients across a network. An NFS client grafts a
remote file system onto the client’s local file system name space and makes it behave like a local
UNIX file system. Multiple clients can mount the same remote file system so that users can share
files.
In the early 1980s, it became economically feasible to build workstations, which allowed each
engineer to have a private computer. But, users desired to still have a shared file system for ease of
collaboration. NFS provides exactly that: it allows a user at any workstation to use files stored on a
shared server, a powerful workstation with local disks but often without a graphical display.
NFS also simplifies the management of a collection of workstations. Without NFS, a system
administrator must manage each workstation and, for example, arrange for backups of each
workstation’s local disk. NFS allows for centralized management; for example, a system
administrator needs to back up only the disks of the server to archive the file system. In the 1980s,
the setup had also a cost benefit: NFS allowed organizations to buy workstations without disks,
saving the cost of a disk interface on every workstation and, at the time, the cost of unused disk
space on each workstation.
It should work with existing applications, which means NFS ideally should provide the same
semantics as a local UNIX file system.
NFS should be deployable easily, which means its implementation should be able to retrofit
into existing UNIX systems.
The client should be implementable in other operating systems such as Microsoft’s DOS, so
that a user on a personal computer can have access to the files on an NFS server; this goal
implies that the client design cannot be too UNIX-specific.
Finally, NFS should be efficient enough to be tolerable to users, but it doesn’t have to
provide as high performance as local file systems. NFS only partially achieves these goals.
NFS Architecture:
User programs can name remote files in the same way as local files. When a user program invokes,
say, OPEN (“/users/smith/.profile”, READONLY), it cannot tell from the path name whether “users”
or “smith” are local or remote directories.
To make naming remote file transparent to users and their programs, the client must mount the root
directory of a remote file system on the local name space. NFS performs this operation by using a
separate program, called the mounter. This program serves a similar function as the MOUNT call; it
grafts the remote file system— named by host:path, where host is a DNS name and path a path
name—onto the local file name space. The mounter sends a remote procedure call to the file server
host and asks for a file handle, a 32-byte name, for the inode of path. On receiving the reply, the
client marks the mount point in the local file system as a remote file system. It also remembers the
file handle for path and the network address for the server.
NFS doesn’t use path names to name files and directories internally, but instead uses file handles. To
the client a file handle is a 32-byte opaque name that identifies an inode on a remote server. A client
obtains file handles from the server when the client mounts a remote file system or it looks up a file
in a directory on the server. In all subsequent remote procedures calls to the server for that file, the
client includes the file handle.
File handles are usable names across server failures, so that even if the server computer fails
between a client program opening a file and then reading from the file, the server can identify the
file using the information in the file handle.
The above figure shows the corresponding timing diagram where ‘f’ is a remote file. The NFS client
implements each file system operation using one or remote procedure calls. In response to the
program’s call to OPEN, the NFS client sends the following remote procedure call to the server:
From before the program runs, the client has a file handle for the current working directory's (dirfh).
It obtained this handle as a result of a previous lookup or as a result of mounting the remote file
system.
On receiving the LOOKUP request, the NFS server extracts the file system identifier from dirfh, and
asks the identified file system to look up the inode for dirfh. The identified file system uses the inode
number in dirfh to locate the directory’s inode. Now the NFS server searches the directory for the
inode for “f”. If present, the server creates a handle for the “f”. The handle contains the file system
identifier of the local file system, the inode number for “f”, and the generation number stored in f’s
inode. The NFS server sends this file handle to the client.
On receiving the response, the client allocates the first unused entry in the program’s file descriptor
table, stores a reference to f’s file handle in that entry, and returns the index for the entry (fd) to the
user program.
Next, the program calls READ (fd, buf, n). The client sends the following remote procedure call to the
NFS server:
Like with the directory file handle, the NFS server looks up the inode for fh. Then, the server reads
the data and sends the data in a reply message to the client. The NFS remote procedure calls are
designed so that the server can be stateless, that is the server doesn’t need to maintain any other
state than the on-disk files. NFS achieves this property by making each remote procedure call
contain all the information necessary to carry out that request. The server does not maintain any
state about past remote procedure calls to process a new request.
A partition is a division of a logical database or its constituting elements into distinct independent
parts. Database partitioning is normally done for manageability, performance or availability reasons.
46 Distributed Systems Lab
Date: Roll no. : 0208-8110
The partitioning can be done by either building separate smaller databases (each with its own tables,
indices, and transaction logs), or by splitting selected elements, for example just one table.
Horizontal partitioning (also see shard) involves putting different rows into different tables. Perhaps
customers with ZIP codes less than 50000 are stored in CustomersEast, while customers with ZIP
codes greater than or equal to 50000 are stored in CustomersWest. The two partition tables are
then CustomersEast and CustomersWest, while a view with a union might be created over both of
them to provide a complete view of all customers.
Vertical partitioning involves creating tables with fewer columns and using additional tables to store
the remaining columns. Normalization also involves this splitting of columns across tables, but
vertical partitioning goes beyond that and partitions columns even when already normalized. Done
explicitly or implicitly, this type of partitioning is called "row splitting" (the row is split by its
columns). A common form of vertical partitioning is to split (slow to find) dynamic data from (fast to
find) static data in a table where the dynamic data is not used as often as the static. Creating a view
across the two newly created tables restores the original table with a performance penalty, however
performance will increase when accessing the static data e.g. for statistical analysis.
Partitioning criteria:
Current high end relational database management systems provide for different criteria to split the
database. They take a partitioning key and assign a partition based on certain criteria. Common
criteria are:
47 Distributed Systems Lab
Date: Roll no. : 0208-8110
1. Range partitioning
Selects a partition by determining if the partitioning key is inside a certain range. An example
could be a partition for all rows where the column zipcode has a value between 70000 and 79999.
Code:
Table created.
2. List partitioning
A partition is assigned a list of values. If the partitioning key has one of these values, the partition
is chosen. For example all rows where the column Country is either Iceland, Norway, Sweden,
Finland or Denmark could build a partition for the Nordic countries.
Code:
Table created.
3. Hash partitioning
The value of a hash function determines membership in a partition. Assuming there are four
partitions, the hash function could return a value from 0 to 3.
Code:
Composite partitioning allows for certain combinations of the above partitioning schemes, for
example first applying a range partitioning and then a hash partitioning. Consistent hashing could be
considered a composite of hash and list partitioning where the hash reduces the key space to a size
that can be listed.
To view a partition:
Database replication is the creation and maintenance of multiple copies of the same database. In
most implementations of database replication, one database server maintains the master copy of
the database and additional database servers maintain slave copies of the database. Database writes
are sent to the master database server and are then replicated by the slave database servers.
Database reads are divided among all of the database servers, which results in a large performance
advantage due to load sharing. In addition, database replication can also improve availability
because the slave database servers can be configured to take over the master role if the master
database server becomes unavailable.
Master Slave
Step 1: Step 1:
mysql> GRANT REPLICATION SLAVE mysql> CHANGE MASTER TO
-> ON *.* TO 'user_name'@'master_host' -> MASTER_HOST='master_host',
-> IDENTIFIED BY 'user_password'; -> MASTER_PORT=master_port,
-> MASTER_USER='slave_user',
-> MASTER_PASSWORD='slave_password';
Step 2: Step 3:
mysql> SHOW MASTER STATUS\G; mysql> CHANGE MASTER TO
Once you have obtain the Master Status, please -> MASTER_LOG_FILE='[file]',
note down the 2 most important info, which is -> MASTER_LOG_POS=[position];
50 Distributed Systems Lab
Date: Roll no. : 0208-8110
Step 3: Step 5:
To show master status, use the following To show slave status, use the following
command command
mysql> SHOW MASTER STATUS\G; mysql> SHOW SLAVE STATUS\G;
mysql> SHOW PROCESSLIST\G; mysql> SHOW PROCESSLIST\G;