SlideShare a Scribd company logo
1 of 52
www.SunilOS.com 1
JAVA Networking
www.sunilos.com
www.raystec.com
Agenda
Elements of Client Server Computing
Network Basics
Understanding Ports and Sockets
Java Sockets
o Implementing a Server
o Implementing a Client
Sample Examples
Conclusion
www.SunilOS.com 2
What is Networking?
When two processes, lying on same or
different machines are communicating
over the network is called networking.
www.SunilOS.com 3
Client Server
Server & Client
Process providing
services is called
Server.
Process consuming
services is called Client
www.SunilOS.com 4
www.SunilOS.com 5
Elements of Client-Server computing
Network
Request
Response
There are three elements in networking
 Client : sends request for services
 Server : sends response
 Network : media of communication
Client
Server
Client Machine Server Machine
Single Machine Multiple Clients
www.SunilOS.com 6
Yahoo
Server
Google
Server
Hotmail
Server
Client’s Machine
One Machine can execute multiple clients’ processes concurrently
Client is a Process
 One machine may run multiple clients (processes) at a time.
 Client is not a machine, it is a process.
o Browser opens google.com is a Client.
o Yahoo Messenger connected to chat server is a client.
o CuteFTP uploading a file to FTP Server is a Client.
 All above mentioned clients (CuteFTP, Messenger,
Browser) run together on a single Machine concurrently.
www.SunilOS.com 7
Client Machine
Crome Browser
Yahoo Messenger
CuteFTP
Process 4
Server is a Process
 One machine may run multiple servers (processes) at a
time.
 Server is not a machine, it is a process.
o Tomcat Web Server is a process.
o WAMP PHP Server is a process.
o Filezilla FTP Server is a process.
 All above mentioned servers run together on a single
Machine concurrently.
www.SunilOS.com 8
Single Machine Multiple Servers
www.SunilOS.com 9
Server Machine
Tomcat Web
Server (Port : 8080)
FileZilla FTP
Server (Port : 21)
WAMP PHP
Server (Port : 80)
Server & Client
 Since Operating Systems can execute multiple processes
concurrently using preemptive scheduling. Thus, one
Machine may run multiple Servers and Clients together.
 Client and Server processes communicate over the network
to exchange data in form of request and response.
www.SunilOS.com 10
Machine
Crome Browser
Yahoo Messenger
Tomcat
WAMP
How Clients and Servers are identified?
Clients and Servers are uniquely identified on a
single machine by unique Port Numbers.
Unique Port Number is assigned by OS.
Process can ask desired port number from OS, or
OS will assign next available port number to a
process.
Port number is a two bytes unsigned number
ranging from 0-65535.
www.SunilOS.com 11
Ports
www.SunilOS.com 12
Server Machine
Tomcat Web
Server
FileZilla FTP
Server
WAMP PHP
Server
8080
21
80
Client Machine
Browser
FTP Client
Browser
1111
2222
3333
Communication Rules (Protocols)
www.SunilOS.com 13
Hello, I am Vijay, May
I talk to Tisha
Yes, I m Tisha
Blah, Blah, Blah .....
………………………
….
Bye
Have a Good Day
Certain rules are followed when you communicate over the network,
are called Protocols
Protocol over Phone
When you call someone over phone and start
conversation, you follow protocol.
First you greet and say “Hello” , then you tell your
name “I am Vijay”, then you ask with whom you
want to talk “May I talk to Tisha?” .
Likewise when conversation is over you say “Bye”
and other would respond “Have a Good Day”.
This is Protocol
www.SunilOS.com 14
Protocol Responsibilities
Applies a set of Rules.
Converts your application data into byte stream
and vice versa.
Breaks data into packets and sends over network.
Receives acknowledgements of sent packets.
Decides network route to send data packets.
www.SunilOS.com 15
Protocol Stack
 A group of network protocols that work together to send and
receive your data over the network, is called a Protocol
Stack.
 The TCP/IP protocol stack uses four layers that map to the
OSI model:
www.SunilOS.com 16
Application
(http,ftp,telnet,…)
Transport
(TCP, UDP,..)
Network
(IP,..)
Link
(device driver,..)
Protocol Stack Communication
www.SunilOS.com 17
Application
(http,ftp,telnet,…)
Transport
(TCP, UDP,..)
Network
(IP,..)
Link
(device driver,..)
Application
(http,ftp,telnet,…)
Transport
(TCP, UDP,..)
Network
(IP,..)
Link
(device driver,..)
TCP/IP Protocol Stack
Applications Layer:
o contains user custom and high level application protocols
like HTTP, FTP, SMTP, Telnet etc.
Transport Layer:
o Contains TCP or UDP protocols, responsible for making
data packets and send or receive across network.
o Your custom application will communicate to this layer.
Network Layer:
o contains IP Protocol that uses routing information to
decide route of data packet to send it to the destination.
Link Layer:
o converts data into signals.
www.SunilOS.com 18
TCP Protocols
TCP (Transport Control Protocol) is a connection-
oriented protocol that provides a reliable flow of
data between two computers.
Example applications:
o HTTP
o FTP
o Telnet
www.SunilOS.com 19
UDP Protocols
UDP (User Datagram Protocol): It is a protocol that
sends independent packets of data (called
datagrams ) from one computer to another with NO
guarantee about arrival.
Example applications:
o Clock server
o Ping
www.SunilOS.com 20
www.SunilOS.com 21
Network Ports
 The TCP and UDP
protocols use ports to map
incoming data to a
particular process running
on a computer.
server
P
o
r
t
Client
TCP
TCP or UDP
port1 port2 port3 port4
app1 app2 app3 app4
port# data
Data
Packets
Port
port# data
port4 data
Ports
 Port number is a two bytes unsigned number ranging from
0-65535.
 Some ports have been reserved to support common/well
known services:
o ftp 21/tcp
o telnet 23/tcp
o smtp 25/tcp
o http 80/tcp
 Developer defined processes/services are advised to use
port numbers >= 1024 because port numbers <1024 are
reserved for special services.
www.SunilOS.com 22
www.SunilOS.com 23
Sockets
Server
255.255.192.101
Client
192.168.125.1108080 1234
Socket = IP+ Port
Server Socket = 255.255.192.101:8080
Client Socket = 192.168.125.110:1234
port# data
Server and Client have network end points called sockets. Sockets are
bound to a specific port.
www.SunilOS.com 24
Java Socket Classes
Java provides socket classes to make
Server and Client.
Package java.net contains socket
classes.
There are separate classes for TCP and
UDP connections.
Make TCP Connection
Following classes are used in Java to make TCP
connection.
o java.net.Socket – for client implementation
o java.net.ServerSocket – for server implementation
www.SunilOS.com 25
Make UDP Connection
Following classes are used in Java to make UDP
connection.
o java.net.DatagramSocket – for client and server
implementation
o java.net.DatagramPacket – for making data packets
www.SunilOS.com 26
www.SunilOS.com 27
Create TCP Server
 Class ServerSocket creates a TCP server and waits for
Client request.
o ServerSocket ss = new ServerSocket(4444);
o Socket client = ss.accept() ;
 Server is bound to port number 4444.
 Server is waiting for client request by calling method
ss.accept().
server Client
Connection request
4444
ss
www.SunilOS.com 28
Create TCP Client
 Class Socket creates a TCP client.
 Server IP and Port number are passed to Socket
parametrized constructor.
Socket client=new Socket(“127.0.0.1”,4444);
 Created socket instance will establish connection with
server.
www.SunilOS.com 29
Java Sockets
ServerSocket(1234)
Socket(“128.250.25.158”, 1234)
Output/write stream
Input/read stream
It can be host_name like “www.sunilos.com”
Client
Server
128.250.25.158
www.SunilOS.com 30
Sockets IO
Sockets provide an interface for programming
networks at the transport layer.
Network communication using Sockets is very
much similar to performing file I/O
o The streams used in file I/O operation are also applicable
to socket-based I/O
Socket-based communication is programming
language independent.
o That means, a socket program written in Java language
can also communicate to a program written in Java or
non-Java socket program.
Read and Write from Socket
IO classes are used to read and write byte streams
from the Socket.
 Socket s=new Socket(“127.0.0.1”,4444);//Client Side
 Or
 Socket s=ss.accept();//Server Side
 DataOutputStream os;
 DataInputStream is;
 is=new DataInputStream(s.getInputStream());
 os=new DataOutputStream(s.getOutputStream());
 String line = is.readLine(); //Read from Socket
 os.writeBytes("Hellon"); //Write to Socket
www.SunilOS.com 31
Network Communication
www.SunilOS.com 32
www.SunilOS.com 33
Client and Server Communication
 1: ServerSocket server =
new ServerSocket(1234);
 2: Socket client =
server.accept();
 4: in = new DataInputStream(
client.getInputStream())
 5: out=new DataOutputStream(
client.getOutputStream())
 7:String line=in.readLine();
 8:out.writeBytes(
 "Hello Clientn")
 10:client.close()
 3: Socket client = new
Socket(“localhost”,1234);
 4: in = new DataInputStream(
client.getInputStream())
 5: out=new DataOutputStream(
client.getOutputStream())
 6: out.writeBytes("Hello
Servern")
 9:String line=in.readLine();
 10:client.close()
1234
Server
Client
port
Client
in
out
out
in
Hello Server
Hello Client
www.SunilOS.com 34
Echo Client and Server
Echo Server echoes the text sent by Client.
Uses TCP Protocol.
Server will handle multiple Clients sequentially.
Server will end communication when Client sends
“Bye”.
Server
Client
Hello .. Hello
Hello
www.SunilOS.com 35
Echo Server
public static void main(String[] args) throws IOException {
ServerSocket ss= new ServerSocket(4444);
System.out.println("Echo Server Started");
Socket client= null;
boolean flag = true;
while (flag) {
client = ss.accept(); //Accept Client
talk(client); //Talk to the client
}
System.out.println("Echo Server Stopped");
ss.close(); //Close server
}
www.SunilOS.com 36
Echo Server (Cont.)
public static void talk(Socket client) throws IOException {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
String msg =null;
msg = in.readLine();
while (msg != null) {
System.out.println("Server Received " + msg);
out.println(msg + " .. " + msg);
if (msg.equals("Bye")) break;
msg = in.readLine();
}
out.close();
in.close();
client.close();
}
www.SunilOS.com 37
Multi-Threaded Echo Server
Handles multiple Clients concurrently
public class TalkingThread extends Thread {
private Socket client= null;
public TalkingThread (Socket client) {
this.client = client;
}
public void run() {
//…See next slide
www.SunilOS.com 38
Multi-Threaded Echo Server (Cont.)
public void run() {
try {
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
String inputLine = in.readLine();
while (inputLine != null) {
System.out.println("Server Recived " + inputLine);
out.println(inputLine + " .. " + inputLine);
if (inputLine.equals("Bye"))
break;
inputLine = in.readLine();
}
out.close(); in.close(); client.close();
} catch (IOException e) { //…}
}
www.SunilOS.com 39
Multi-Threaded Echo Server (Cont.)
 Starts Multithreaded Server
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(4444);
Socket clientSocket = null;
boolean flag = true;
while (flag) {
client = server.accept();
TalkingThread t = new TalkingThread(client);
t.start();
}
System.out.println("Echo Server Stopped”);
server.close();
}
www.SunilOS.com 40
Echo Client
Socket echoSocket = new Socket("127.0.0.1", 4444);
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in)); //Read text from Keyboard
String userInput= stdIn.readLine();
while (userInput != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
if ("Bye.".equals(userInput)) {
break;
}
userInput = stdIn.readLine();
} echoSocket.close();
www.SunilOS.com 41
Socket Exception Handling
try {
Socket client = new Socket(host, port); handleConnection(client);
} catch(UnknownHostException uhe) {
System.out.println(“Server not Found: " + host);
}catch(IOException ioe) {
System.out.println(“Likhana Padna Mushkil hai”);
}
www.SunilOS.com 42
UDP Communication
Server
DatagramSocket(4445)
Client
DatagramSocket()
Mail
DatagramPacket()
send()
receive()
receive() send()
www.SunilOS.com 43
Quote Server
Quote UDP Server,
Receives empty packet from Client
Replies to the Client with a random quote of
the day.
www.SunilOS.com 44
Quote Server
String[] quotes = { "Bura mat Dekho", "Bura Mat kaho", "Bura mat suno" };
DatagramSocket socket = new DatagramSocket(4445);
byte[] buf = new byte[256];
DatagramPacket emptyPkt = new DatagramPacket(buf, buf.length);
while (true) { //Infinite loop
socket.receive(emptyPkt);
InetAddress address = emptyPkt.getAddress();
int port = emptyPkt.getPort();
int ind = Math.random()*2; //get random index
String q= quotes[ind]; // Today’s quote";
byte[] quoteBuf = q.getBytes();
DatagramPacket quotePkt = new DatagramPacket(quoteBuf,
quoteBuf.length, address, port);
socket.send( quotePkt );
}
www.SunilOS.com 45
Quote Client
 Sends empty packet and receives Quote of the Moment.
DatagramSocket socket = new DatagramSocket();
// send request
byte[] buf = new byte[256];
InetAddress address = InetAddress.getByName("localhost");
DatagramPacket packet = new DatagramPacket(buf, buf.length, address,4445);
socket.send(packet);
// get response
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// display response
String received = new String(packet.getData());
System.out.println("Quote of the Moment: " + received);
socket.close();
www.SunilOS.com 46
Read From URL
Reads text from URL
public static void main(String[] args) throws IOException {
InputStream inStream = null; URL u = null;
try {
u = new URL("http://www.yahoo.com");
inStream = u.openStream();
} catch (Exception e) {
System.out.println("Error in URL");
System.exit(0);
}
Scanner in = new Scanner(inStream);
while (in.hasNext()) {
System.out.println(in.nextLine());
}
in.close();
}
import java.util.Scanner;
import java.net.URL;
import java.io.*;
www.SunilOS.com 47
Read from URL (Cont.)
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yahooConnection = yahoo.openConnection();
yahooConnection.connect();
InputStream inStream = yahooConnection.getInputStream();
Scanner in = new Scanner(inStream);
while (in.hasNext()) {
System.out.println(in.nextLine());
}
inStream.close();
}
www.SunilOS.com 48
Write to URL
URL url = new URL("http://search.yahoo.com/search");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
String nameParameter = “books” //URLEncoder.encode("books", "UTF-8");
out.write("p=" + nameParameter);
out.write("&param2=abc");
out.close();
InputStream inStream = connection.getInputStream();
Scanner in = new Scanner(inStream);
while (in.hasNext()) {
System.out.println(in.nextLine());
}in.close();
www.SunilOS.com 49
Java.net.URL
 Interesting Methods
 getProtocol
o Returns the protocol identifier component of the URL.
 getAuthority
o Returns the authority component of the URL.
 getHost
o Returns the host name component of the URL.
 getPort
o Returns the port number component of the URL. The getPort method returns an
integer that is the port number. If the port is not set, getPort returns -1.
 getPath
o Returns the path component of this URL.
 getQuery
o Returns the query component of this URL.
 getFile
o Returns the filename component of the URL. The getFile method returns the same as
getPath, plus the concatenation of the value of getQuery, if any.
 getRef
• Returns the reference component of the URL.
www.SunilOS.com 50
Assigment
Create a chat server and chat client
Data will be sent by UDP protocol
Server will be multithreaded
Client messenger window will be implemented by
Swing.
Disclaimer
This is an educational presentation to enhance the
skill of computer science students.
This presentation is available for free to computer
science students.
Some internet images from different URLs are
used in this presentation to simplify technical
examples and correlate examples with the real
world.
We are grateful to owners of these URLs and
pictures.
www.SunilOS.com 51
Thank You!
www.SunilOS.com 52
www.SunilOS.com

More Related Content

What's hot

Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)Manisha Keim
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in javasharma230399
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycleDhruvin Nakrani
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Socket programming
Socket programmingSocket programming
Socket programmingharsh_bca06
 
graphics programming in java
graphics programming in javagraphics programming in java
graphics programming in javaAbinaya B
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Elizabeth alexander
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state managementpriya Nithya
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 

What's hot (20)

Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in java
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Java rmi
Java rmiJava rmi
Java rmi
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Servlets
ServletsServlets
Servlets
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
URL Class in JAVA
URL Class in JAVAURL Class in JAVA
URL Class in JAVA
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Socket programming
Socket programmingSocket programming
Socket programming
 
graphics programming in java
graphics programming in javagraphics programming in java
graphics programming in java
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

Viewers also liked

Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket ProgrammingMousmi Pawar
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Java ME Networking & Connectivity
Java ME Networking & ConnectivityJava ME Networking & Connectivity
Java ME Networking & ConnectivityStefano Sanna
 
Java networking programs socket based
Java networking programs socket basedJava networking programs socket based
Java networking programs socket basedMukesh Tekwani
 
Open Distributed Networking Intelligence: A New Java Paradigm
Open Distributed Networking Intelligence: A New Java ParadigmOpen Distributed Networking Intelligence: A New Java Paradigm
Open Distributed Networking Intelligence: A New Java ParadigmTal Lavian Ph.D.
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkArun Mehra
 
Resource Bundle
Resource BundleResource Bundle
Resource BundleSunil OS
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsRakesh Waghela
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)Om Ganesh
 

Viewers also liked (20)

JDBC
JDBCJDBC
JDBC
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
java networking
 java networking java networking
java networking
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Networking in java
Networking in javaNetworking in java
Networking in java
 
Java ME Networking & Connectivity
Java ME Networking & ConnectivityJava ME Networking & Connectivity
Java ME Networking & Connectivity
 
Java networking programs socket based
Java networking programs socket basedJava networking programs socket based
Java networking programs socket based
 
Java RMI
Java RMIJava RMI
Java RMI
 
Hibernate & JPA perfomance
Hibernate & JPA perfomance Hibernate & JPA perfomance
Hibernate & JPA perfomance
 
Open Distributed Networking Intelligence: A New Java Paradigm
Open Distributed Networking Intelligence: A New Java ParadigmOpen Distributed Networking Intelligence: A New Java Paradigm
Open Distributed Networking Intelligence: A New Java Paradigm
 
javanetworking
javanetworkingjavanetworking
javanetworking
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 

Similar to JAVA Networking: Client-Server Communication Using Sockets and Ports

Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagarNitish Nagar
 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptxRoshniSundrani
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Socket Programming by Rajkumar Buyya
Socket Programming by Rajkumar BuyyaSocket Programming by Rajkumar Buyya
Socket Programming by Rajkumar BuyyaiDhawalVaja
 
Design an Implementation of A Messaging and Resource Sharing Software
Design an Implementation of A Messaging and Resource Sharing SoftwareDesign an Implementation of A Messaging and Resource Sharing Software
Design an Implementation of A Messaging and Resource Sharing Softwarenilabarai
 
Network Programming-Python-13-8-2023.pptx
Network Programming-Python-13-8-2023.pptxNetwork Programming-Python-13-8-2023.pptx
Network Programming-Python-13-8-2023.pptxssuser23035c
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programmingGera Paulos
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in JavaTushar B Kute
 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project ReportKavita Sharma
 
Chat server nitish nagar
Chat server nitish nagarChat server nitish nagar
Chat server nitish nagarNitish Nagar
 
Final networks lab manual
Final networks lab manualFinal networks lab manual
Final networks lab manualJaya Prasanna
 
Lan chat system
Lan chat systemLan chat system
Lan chat systemWipro
 
How a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdfHow a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdfarccreation001
 
Networking.pptx
Networking.pptxNetworking.pptx
Networking.pptxEsubesisay
 
Intro to web services
Intro to web servicesIntro to web services
Intro to web servicesNeil Ghosh
 

Similar to JAVA Networking: Client-Server Communication Using Sockets and Ports (20)

Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Sockets
SocketsSockets
Sockets
 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptx
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket Programming by Rajkumar Buyya
Socket Programming by Rajkumar BuyyaSocket Programming by Rajkumar Buyya
Socket Programming by Rajkumar Buyya
 
Design an Implementation of A Messaging and Resource Sharing Software
Design an Implementation of A Messaging and Resource Sharing SoftwareDesign an Implementation of A Messaging and Resource Sharing Software
Design an Implementation of A Messaging and Resource Sharing Software
 
Network Programming-Python-13-8-2023.pptx
Network Programming-Python-13-8-2023.pptxNetwork Programming-Python-13-8-2023.pptx
Network Programming-Python-13-8-2023.pptx
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programming
 
Python networking
Python networkingPython networking
Python networking
 
28 networking
28  networking28  networking
28 networking
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in Java
 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project Report
 
A.java
A.javaA.java
A.java
 
Chat server nitish nagar
Chat server nitish nagarChat server nitish nagar
Chat server nitish nagar
 
Final networks lab manual
Final networks lab manualFinal networks lab manual
Final networks lab manual
 
Lan chat system
Lan chat systemLan chat system
Lan chat system
 
How a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdfHow a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdf
 
Networking.pptx
Networking.pptxNetworking.pptx
Networking.pptx
 
Intro to web services
Intro to web servicesIntro to web services
Intro to web services
 

More from Sunil OS

Threads V4
Threads  V4Threads  V4
Threads V4Sunil OS
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4Sunil OS
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3Sunil OS
 
Threads v3
Threads v3Threads v3
Threads v3Sunil OS
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3Sunil OS
 
Collection v3
Collection v3Collection v3
Collection v3Sunil OS
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJSunil OS
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )Sunil OS
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )Sunil OS
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )Sunil OS
 
Python Pandas
Python PandasPython Pandas
Python PandasSunil OS
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1Sunil OS
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
Python Part 1
Python Part 1Python Part 1
Python Part 1Sunil OS
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and OperatorsSunil OS
 

More from Sunil OS (20)

Threads V4
Threads  V4Threads  V4
Threads V4
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
 
DJango
DJangoDJango
DJango
 
PDBC
PDBCPDBC
PDBC
 
OOP v3
OOP v3OOP v3
OOP v3
 
Threads v3
Threads v3Threads v3
Threads v3
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
 
Collection v3
Collection v3Collection v3
Collection v3
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
 
C# Basics
C# BasicsC# Basics
C# Basics
 

Recently uploaded

Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineCeline George
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...Nguyen Thanh Tu Collection
 
The role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipThe role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipKarl Donert
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6Vanessa Camilleri
 
Unit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceUnit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceDr Vijay Vishwakarma
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroomSamsung Business USA
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 
physiotherapy in Acne condition.....pptx
physiotherapy in Acne condition.....pptxphysiotherapy in Acne condition.....pptx
physiotherapy in Acne condition.....pptxAneriPatwari
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxryandux83rd
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
Shark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsShark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsArubSultan
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Osopher
 
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...DrVipulVKapoor
 

Recently uploaded (20)

Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command Line
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
 
The role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipThe role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenship
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6
 
Unit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceUnit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional Intelligence
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
physiotherapy in Acne condition.....pptx
physiotherapy in Acne condition.....pptxphysiotherapy in Acne condition.....pptx
physiotherapy in Acne condition.....pptx
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptx
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
Shark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsShark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristics
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
 
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
 

JAVA Networking: Client-Server Communication Using Sockets and Ports

  • 2. Agenda Elements of Client Server Computing Network Basics Understanding Ports and Sockets Java Sockets o Implementing a Server o Implementing a Client Sample Examples Conclusion www.SunilOS.com 2
  • 3. What is Networking? When two processes, lying on same or different machines are communicating over the network is called networking. www.SunilOS.com 3 Client Server
  • 4. Server & Client Process providing services is called Server. Process consuming services is called Client www.SunilOS.com 4
  • 5. www.SunilOS.com 5 Elements of Client-Server computing Network Request Response There are three elements in networking  Client : sends request for services  Server : sends response  Network : media of communication Client Server Client Machine Server Machine
  • 6. Single Machine Multiple Clients www.SunilOS.com 6 Yahoo Server Google Server Hotmail Server Client’s Machine One Machine can execute multiple clients’ processes concurrently
  • 7. Client is a Process  One machine may run multiple clients (processes) at a time.  Client is not a machine, it is a process. o Browser opens google.com is a Client. o Yahoo Messenger connected to chat server is a client. o CuteFTP uploading a file to FTP Server is a Client.  All above mentioned clients (CuteFTP, Messenger, Browser) run together on a single Machine concurrently. www.SunilOS.com 7 Client Machine Crome Browser Yahoo Messenger CuteFTP Process 4
  • 8. Server is a Process  One machine may run multiple servers (processes) at a time.  Server is not a machine, it is a process. o Tomcat Web Server is a process. o WAMP PHP Server is a process. o Filezilla FTP Server is a process.  All above mentioned servers run together on a single Machine concurrently. www.SunilOS.com 8
  • 9. Single Machine Multiple Servers www.SunilOS.com 9 Server Machine Tomcat Web Server (Port : 8080) FileZilla FTP Server (Port : 21) WAMP PHP Server (Port : 80)
  • 10. Server & Client  Since Operating Systems can execute multiple processes concurrently using preemptive scheduling. Thus, one Machine may run multiple Servers and Clients together.  Client and Server processes communicate over the network to exchange data in form of request and response. www.SunilOS.com 10 Machine Crome Browser Yahoo Messenger Tomcat WAMP
  • 11. How Clients and Servers are identified? Clients and Servers are uniquely identified on a single machine by unique Port Numbers. Unique Port Number is assigned by OS. Process can ask desired port number from OS, or OS will assign next available port number to a process. Port number is a two bytes unsigned number ranging from 0-65535. www.SunilOS.com 11
  • 12. Ports www.SunilOS.com 12 Server Machine Tomcat Web Server FileZilla FTP Server WAMP PHP Server 8080 21 80 Client Machine Browser FTP Client Browser 1111 2222 3333
  • 13. Communication Rules (Protocols) www.SunilOS.com 13 Hello, I am Vijay, May I talk to Tisha Yes, I m Tisha Blah, Blah, Blah ..... ……………………… …. Bye Have a Good Day Certain rules are followed when you communicate over the network, are called Protocols
  • 14. Protocol over Phone When you call someone over phone and start conversation, you follow protocol. First you greet and say “Hello” , then you tell your name “I am Vijay”, then you ask with whom you want to talk “May I talk to Tisha?” . Likewise when conversation is over you say “Bye” and other would respond “Have a Good Day”. This is Protocol www.SunilOS.com 14
  • 15. Protocol Responsibilities Applies a set of Rules. Converts your application data into byte stream and vice versa. Breaks data into packets and sends over network. Receives acknowledgements of sent packets. Decides network route to send data packets. www.SunilOS.com 15
  • 16. Protocol Stack  A group of network protocols that work together to send and receive your data over the network, is called a Protocol Stack.  The TCP/IP protocol stack uses four layers that map to the OSI model: www.SunilOS.com 16 Application (http,ftp,telnet,…) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)
  • 17. Protocol Stack Communication www.SunilOS.com 17 Application (http,ftp,telnet,…) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..) Application (http,ftp,telnet,…) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)
  • 18. TCP/IP Protocol Stack Applications Layer: o contains user custom and high level application protocols like HTTP, FTP, SMTP, Telnet etc. Transport Layer: o Contains TCP or UDP protocols, responsible for making data packets and send or receive across network. o Your custom application will communicate to this layer. Network Layer: o contains IP Protocol that uses routing information to decide route of data packet to send it to the destination. Link Layer: o converts data into signals. www.SunilOS.com 18
  • 19. TCP Protocols TCP (Transport Control Protocol) is a connection- oriented protocol that provides a reliable flow of data between two computers. Example applications: o HTTP o FTP o Telnet www.SunilOS.com 19
  • 20. UDP Protocols UDP (User Datagram Protocol): It is a protocol that sends independent packets of data (called datagrams ) from one computer to another with NO guarantee about arrival. Example applications: o Clock server o Ping www.SunilOS.com 20
  • 21. www.SunilOS.com 21 Network Ports  The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer. server P o r t Client TCP TCP or UDP port1 port2 port3 port4 app1 app2 app3 app4 port# data Data Packets Port port# data port4 data
  • 22. Ports  Port number is a two bytes unsigned number ranging from 0-65535.  Some ports have been reserved to support common/well known services: o ftp 21/tcp o telnet 23/tcp o smtp 25/tcp o http 80/tcp  Developer defined processes/services are advised to use port numbers >= 1024 because port numbers <1024 are reserved for special services. www.SunilOS.com 22
  • 23. www.SunilOS.com 23 Sockets Server 255.255.192.101 Client 192.168.125.1108080 1234 Socket = IP+ Port Server Socket = 255.255.192.101:8080 Client Socket = 192.168.125.110:1234 port# data Server and Client have network end points called sockets. Sockets are bound to a specific port.
  • 24. www.SunilOS.com 24 Java Socket Classes Java provides socket classes to make Server and Client. Package java.net contains socket classes. There are separate classes for TCP and UDP connections.
  • 25. Make TCP Connection Following classes are used in Java to make TCP connection. o java.net.Socket – for client implementation o java.net.ServerSocket – for server implementation www.SunilOS.com 25
  • 26. Make UDP Connection Following classes are used in Java to make UDP connection. o java.net.DatagramSocket – for client and server implementation o java.net.DatagramPacket – for making data packets www.SunilOS.com 26
  • 27. www.SunilOS.com 27 Create TCP Server  Class ServerSocket creates a TCP server and waits for Client request. o ServerSocket ss = new ServerSocket(4444); o Socket client = ss.accept() ;  Server is bound to port number 4444.  Server is waiting for client request by calling method ss.accept(). server Client Connection request 4444 ss
  • 28. www.SunilOS.com 28 Create TCP Client  Class Socket creates a TCP client.  Server IP and Port number are passed to Socket parametrized constructor. Socket client=new Socket(“127.0.0.1”,4444);  Created socket instance will establish connection with server.
  • 29. www.SunilOS.com 29 Java Sockets ServerSocket(1234) Socket(“128.250.25.158”, 1234) Output/write stream Input/read stream It can be host_name like “www.sunilos.com” Client Server 128.250.25.158
  • 30. www.SunilOS.com 30 Sockets IO Sockets provide an interface for programming networks at the transport layer. Network communication using Sockets is very much similar to performing file I/O o The streams used in file I/O operation are also applicable to socket-based I/O Socket-based communication is programming language independent. o That means, a socket program written in Java language can also communicate to a program written in Java or non-Java socket program.
  • 31. Read and Write from Socket IO classes are used to read and write byte streams from the Socket.  Socket s=new Socket(“127.0.0.1”,4444);//Client Side  Or  Socket s=ss.accept();//Server Side  DataOutputStream os;  DataInputStream is;  is=new DataInputStream(s.getInputStream());  os=new DataOutputStream(s.getOutputStream());  String line = is.readLine(); //Read from Socket  os.writeBytes("Hellon"); //Write to Socket www.SunilOS.com 31
  • 33. www.SunilOS.com 33 Client and Server Communication  1: ServerSocket server = new ServerSocket(1234);  2: Socket client = server.accept();  4: in = new DataInputStream( client.getInputStream())  5: out=new DataOutputStream( client.getOutputStream())  7:String line=in.readLine();  8:out.writeBytes(  "Hello Clientn")  10:client.close()  3: Socket client = new Socket(“localhost”,1234);  4: in = new DataInputStream( client.getInputStream())  5: out=new DataOutputStream( client.getOutputStream())  6: out.writeBytes("Hello Servern")  9:String line=in.readLine();  10:client.close() 1234 Server Client port Client in out out in Hello Server Hello Client
  • 34. www.SunilOS.com 34 Echo Client and Server Echo Server echoes the text sent by Client. Uses TCP Protocol. Server will handle multiple Clients sequentially. Server will end communication when Client sends “Bye”. Server Client Hello .. Hello Hello
  • 35. www.SunilOS.com 35 Echo Server public static void main(String[] args) throws IOException { ServerSocket ss= new ServerSocket(4444); System.out.println("Echo Server Started"); Socket client= null; boolean flag = true; while (flag) { client = ss.accept(); //Accept Client talk(client); //Talk to the client } System.out.println("Echo Server Stopped"); ss.close(); //Close server }
  • 36. www.SunilOS.com 36 Echo Server (Cont.) public static void talk(Socket client) throws IOException { PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(client.getInputStream())); String msg =null; msg = in.readLine(); while (msg != null) { System.out.println("Server Received " + msg); out.println(msg + " .. " + msg); if (msg.equals("Bye")) break; msg = in.readLine(); } out.close(); in.close(); client.close(); }
  • 37. www.SunilOS.com 37 Multi-Threaded Echo Server Handles multiple Clients concurrently public class TalkingThread extends Thread { private Socket client= null; public TalkingThread (Socket client) { this.client = client; } public void run() { //…See next slide
  • 38. www.SunilOS.com 38 Multi-Threaded Echo Server (Cont.) public void run() { try { PrintWriter out = new PrintWriter(client.getOutputStream(),true); BufferedReader in = new BufferedReader(new InputStreamReader( client.getInputStream())); String inputLine = in.readLine(); while (inputLine != null) { System.out.println("Server Recived " + inputLine); out.println(inputLine + " .. " + inputLine); if (inputLine.equals("Bye")) break; inputLine = in.readLine(); } out.close(); in.close(); client.close(); } catch (IOException e) { //…} }
  • 39. www.SunilOS.com 39 Multi-Threaded Echo Server (Cont.)  Starts Multithreaded Server public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(4444); Socket clientSocket = null; boolean flag = true; while (flag) { client = server.accept(); TalkingThread t = new TalkingThread(client); t.start(); } System.out.println("Echo Server Stopped”); server.close(); }
  • 40. www.SunilOS.com 40 Echo Client Socket echoSocket = new Socket("127.0.0.1", 4444); PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream())); BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); //Read text from Keyboard String userInput= stdIn.readLine(); while (userInput != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); if ("Bye.".equals(userInput)) { break; } userInput = stdIn.readLine(); } echoSocket.close();
  • 41. www.SunilOS.com 41 Socket Exception Handling try { Socket client = new Socket(host, port); handleConnection(client); } catch(UnknownHostException uhe) { System.out.println(“Server not Found: " + host); }catch(IOException ioe) { System.out.println(“Likhana Padna Mushkil hai”); }
  • 43. www.SunilOS.com 43 Quote Server Quote UDP Server, Receives empty packet from Client Replies to the Client with a random quote of the day.
  • 44. www.SunilOS.com 44 Quote Server String[] quotes = { "Bura mat Dekho", "Bura Mat kaho", "Bura mat suno" }; DatagramSocket socket = new DatagramSocket(4445); byte[] buf = new byte[256]; DatagramPacket emptyPkt = new DatagramPacket(buf, buf.length); while (true) { //Infinite loop socket.receive(emptyPkt); InetAddress address = emptyPkt.getAddress(); int port = emptyPkt.getPort(); int ind = Math.random()*2; //get random index String q= quotes[ind]; // Today’s quote"; byte[] quoteBuf = q.getBytes(); DatagramPacket quotePkt = new DatagramPacket(quoteBuf, quoteBuf.length, address, port); socket.send( quotePkt ); }
  • 45. www.SunilOS.com 45 Quote Client  Sends empty packet and receives Quote of the Moment. DatagramSocket socket = new DatagramSocket(); // send request byte[] buf = new byte[256]; InetAddress address = InetAddress.getByName("localhost"); DatagramPacket packet = new DatagramPacket(buf, buf.length, address,4445); socket.send(packet); // get response packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // display response String received = new String(packet.getData()); System.out.println("Quote of the Moment: " + received); socket.close();
  • 46. www.SunilOS.com 46 Read From URL Reads text from URL public static void main(String[] args) throws IOException { InputStream inStream = null; URL u = null; try { u = new URL("http://www.yahoo.com"); inStream = u.openStream(); } catch (Exception e) { System.out.println("Error in URL"); System.exit(0); } Scanner in = new Scanner(inStream); while (in.hasNext()) { System.out.println(in.nextLine()); } in.close(); } import java.util.Scanner; import java.net.URL; import java.io.*;
  • 47. www.SunilOS.com 47 Read from URL (Cont.) public static void main(String[] args) throws Exception { URL yahoo = new URL("http://www.yahoo.com/"); URLConnection yahooConnection = yahoo.openConnection(); yahooConnection.connect(); InputStream inStream = yahooConnection.getInputStream(); Scanner in = new Scanner(inStream); while (in.hasNext()) { System.out.println(in.nextLine()); } inStream.close(); }
  • 48. www.SunilOS.com 48 Write to URL URL url = new URL("http://search.yahoo.com/search"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); String nameParameter = “books” //URLEncoder.encode("books", "UTF-8"); out.write("p=" + nameParameter); out.write("&param2=abc"); out.close(); InputStream inStream = connection.getInputStream(); Scanner in = new Scanner(inStream); while (in.hasNext()) { System.out.println(in.nextLine()); }in.close();
  • 49. www.SunilOS.com 49 Java.net.URL  Interesting Methods  getProtocol o Returns the protocol identifier component of the URL.  getAuthority o Returns the authority component of the URL.  getHost o Returns the host name component of the URL.  getPort o Returns the port number component of the URL. The getPort method returns an integer that is the port number. If the port is not set, getPort returns -1.  getPath o Returns the path component of this URL.  getQuery o Returns the query component of this URL.  getFile o Returns the filename component of the URL. The getFile method returns the same as getPath, plus the concatenation of the value of getQuery, if any.  getRef • Returns the reference component of the URL.
  • 50. www.SunilOS.com 50 Assigment Create a chat server and chat client Data will be sent by UDP protocol Server will be multithreaded Client messenger window will be implemented by Swing.
  • 51. Disclaimer This is an educational presentation to enhance the skill of computer science students. This presentation is available for free to computer science students. Some internet images from different URLs are used in this presentation to simplify technical examples and correlate examples with the real world. We are grateful to owners of these URLs and pictures. www.SunilOS.com 51

Editor's Notes

  1. Limitation with this program is that Server will always be closed after communicating with only one Client.
  2. Now we have separated Client communication logic into a talk() method. This server will handle multiple Clients sequentially
  3. TalkingThread class will create a thread that will talk to the Client concurrently
  4. Run will talk to Client. Once Client will say Bye. It will close communication
  5. It will start Server at port # 4444, then receives Client ‘s socket, create and start a talking thread for this client.