37-Afzal khan-Ajp-Exp 16

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Advanced Java Programming (22517)

Practical No. 16: Write a program to implement chat Server using


Server Socket and Socket Class.

I. Practical Significance:
Java provides the socket programming approach for communication between the
client and server. A user can write the code for both client and server as well for UDP
& TCP datagram packets. By using java’s network communication feature we can
create interactive application to communicate within a network.

II. Relevant Program Outcomes (POs)


 Basic knowledge: Apply knowledge of basic mathematics, sciences and basic
engineering to solve the computer group related problems.
 Discipline knowledge: Apply Computer Programming knowledge to solve the
computer group related problems.
 Experiments and practice: Plan to perform experiments and practices to use the
results to solve the computer group related problems.
 Engineering tools: Apply relevant Computer programming / technologies and
tools with an understanding of the limitations.
 Individual and Team work: Function effectively as a leader and team member in
diverse/multidisciplinary teams.
 Communication: Communicate effectively in oral and written form.

III. Competency and Practical skills


The practical is expected to develop the following skills:
1. Able to develop an application using Socket and ServerSocket class
2. Able to create a chat application in client server environment.

IV. Relevant Course Outcome(s)


Develop java programs using networking components

V. Practical Outcome (PrOs)


Write a program to implement chat server using ServerSocket and Socket class.

VI. Relevant Affective domain related Outcome(s)


1. Follow precautionary measures.
2. Follow naming conventions.
3. Follow ethical practices

VII. Minimum Theoretical Background


The ServerSocket class is used to create servers that listen for either local port or
remote client programs to connect to them on published ports.

Constructors for ServerSocket class


1. public ServerSocket(int port) throws IOException
2. public ServerSocket(int port, int backlog) throws IOException
3. public ServerSocket(int port, int backlog, InetAddress address) throws
IOException
4. public ServerSocket() throws IOException

Maharashtra state Board of Technical Education 85


Advanced Java Programming (22517)

Methods for ServerSocket class


1. public int getLocalPort()
2. public Socket accept() throws IOException
3. public void setSoTimeout(int timeout)
4. public void bind(SocketAddress host, int backlog)

The java.net.Socket class is used to communicate between client and server.The client
can obtain object by creating its instance whereas the server obtains a Socket object
from the return value of the accept() method.

Constructors for Socket class:


1. public Socket(String host, int port) throws UnknownHostException, IOException.
2. public Socket(InetAddress host, int port) throws IOException
3. public Socket(String host, int port, InetAddress localAddress, int localPort) throws
IOException.
4. public Socket(InetAddress host, int port, InetAddress localAddress, int localPort)
throws IOException.
5. public Socket()

Methods for Socket class:


1. public void connect(SocketAddress host, int timeout) throws IOException
2. public InetAddress getInetAddress()
3. public int getPort()
4. public int getLocalPort()
5. public void close() throws IOException

VIII. Resources required (Additional)–

Nil

IX. Resources used (Additional)

Sr.
Name of Resource Broad Specification Quantity Remarks (If any)
No.
1

X. Program Code: Teacher must assign a separate program statement to group of 3-


4 students.
1. Write a program to check credentials of users (Client will send user id and
password to server and server will authenticate the client using equals())

Maharashtra state Board of Technical Education 86


Advanced Java Programming (22517)

XI. Result (Output of Code):

Code:-

 Server Side:
import java.io.*;
import java.net.*;
class MyServer {
private MyServer() {}
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(2019);
System.out.println("Server Started, waiting for client");
Socket s1 = s.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s1.getInputStream()));
String user = br.readLine();
String pass = br.readLine();
OutputStream out = s1.getOutputStream();
PrintStream ps = new PrintStream(out);
if (user.equals("abc") && pass.equals("1234"))
{
ps.println("Validated authenticity");
} else {
ps.println("Validation failure");
}}}

 Client Side:-
import java.io.*;
import java.net.*;
public class MyClient {
private MyClient() {}
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 2019);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Username and Password: ");
String user = br.readLine();
String pass = br.readLine();
OutputStream os = s.getOutputStream();
PrintStream ps = new PrintStream(os);
ps.println(user);
ps.println(pass);
BufferedReader br1 =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String res = br1.readLine();
System.out.println(res);
}}

Maharashtra state Board of Technical Education 87


Advanced Java Programming (22517)

Output:-

Maharashtra state Board of Technical Education 88


Advanced Java Programming (22517)
XII. Practical Related Questions
Note: Below given are few sample questions for reference. Teacher must design
more such questions so as to ensure the achievement of identified CO.
1. Write the default port of used by various services such as FTP, SMTP, HTTP.
2. Write the constructor to allow the server for waiting queue
3. Write the function of Connect(), Bind()

(Space for answer)

Maharashtra state Board of Technical Education 89


Advanced Java Programming (22517)

Maharashtra state Board of Technical Education 90


Advanced Java Programming (22517)

XIII. Exercise:
1. Write a program using Socket and ServerSocket to create Chat Application
2. Write a program to develop prime number Server (Client will send any number to
server, Sever will send the response the number is prime or not)
(Space for Answer)

1. Code:-
 Client Side::
import java.net.*;
import java.io.*;
class MyClient1 {
public static void main(String args[])throws Exception {
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")) {
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}}

 Server Side:
import java.net.*;
import java.io.*;
class MyServer1 {
public static void main(String args[])throws Exception {
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")) {
str=din.readUTF();
System.out.println("Client says: "+str);
str2=br.readLine();
Maharashtra state Board of Technical Education 91
Advanced Java Programming (22517)
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}}

Output:-

Maharashtra state Board of Technical Education 92


Advanced Java Programming (22517)
2. Code:-
 Server Side:
import java.io.*;
import java.net.*;
class MyServer{
private MyServer() {}
public static boolean isPrime(int number) {
boolean isPrimeNum = false;
int i = (int)Math.ceil(Math.sqrt(number));
while (i > 1) {
if ((number != i) && (number % i == 0)) {
isPrimeNum = false;
break;
} else if (!isPrimeNum) {
isPrimeNum = true;
}
--i;
}
return isPrimeNum;
}
public static void main(String[] args) throws Exception {
Socket s;
int port = 9000;
ServerSocket ss = new ServerSocket(port);
System.out.println("Waiting for client");
s = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
int num = Integer.parseInt(br.readLine());
System.out.println("Number sent by client: " + num);
pw.println (MyServer.isPrime(num));
pw.flush();
}}

 Client Side:

import java.io.*;
import java.net.*;
class MyClient {
private MyClient() {}
public static void main(String[] args) throws Exception {
int port = 9000;
Socket s;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s = new Socket(InetAddress.getLocalHost(), port);
PrintWriter pw =
new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader brl = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.print("Enter any number: ");
Maharashtra state Board of Technical Education 93
Advanced Java Programming (22517)
String str = br.readLine();
pw.println(str);
pw.flush();
String msg = brl.readLine();
if (msg.equals("true")) {
System.out.println("It is a prime number");
} else {
System.out.println("It is not a prime number");
}}}

Output:-

Maharashtra state Board of Technical Education 94


Advanced Java Programming (22517)

XIV. References/ Suggestions for Further Reading


1. https://docs.oracle.com/javase/tutorial/networking/sockets/definition.html
2. https://www.tutorialspoint.com/java/java_networking.htm
3. The complete reference Java 2 by Herbert Schildt

XV. Assessment Scheme

Performance Indicators Weightage


Process related (35 Marks) 70%
1. Logic formation 30%
2. Debugging ability 30%
3. Follow ethical practices 10%
Product related (15 Marks) 30%
4. Expected output 10%
5. Timely Submission 10%
6. Answer to sample questions 10%
Total (50 Marks) 100%

List of Students /Team Members

1. …………………………………..
2. …………………………………..
3. …………………………………..

Dated signature
Marks Obtained
of Teacher
Process Product
Total(50)
Related(35) Related(15)

Maharashtra state Board of Technical Education 95

You might also like