SlideShare a Scribd company logo
1 of 46
C603.1 Design GUI using AWT and Swing .
C603.2 Develop program using event handling.
C603.3 Use network concepts (client/server, socket) in the
program.
C603.4 Develop program using JDBC connectivity to access
data from database and execute different queries to
get required result.
C603.5 Develop web based program using servlet and JSP
Course Outcomes of Advanced Java Programming AJP
(17625, C603)
Visit for more Learning Resources
Java Socket Programming
Java Sockets Programming
 The package java.net provides support for
sockets programming (and more).
 Typically you import everything defined in
this package with:
import java.net.*;
Java Socket Programming 3
Classes
InetAddress
Socket
ServerSocket
DatagramSocket
DatagramPacket
Java Socket Programming 4
InetAddress class
 static methods you can use to create new
InetAddress objects.
 getByName(String host)
 getAllByName(String host)
 getLocalHost()
InetAddress x = InetAddress.getByName(
“cse.unr.edu”);
 Throws UnknownHostException
Java Socket Programming 5
Sample Code: Lookup.java
 Uses InetAddress class to lookup hostnames
found on command line.
> java Lookup cse.unr.edu www.yahoo.com
cse.unr.edu:134.197.40.9
www.yahoo.com:209.131.36.158
Java Socket Programming 6
try {
InetAddress a = InetAddress.getByName(hostname);
System.out.println(hostname + ":" +
a.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("No address found for " +
hostname);
}
Java Socket Programming
Socket class
 Corresponds to active TCP sockets only!
 client sockets
 socket returned by accept();
 Passive sockets are supported by a different
class:
 ServerSocket
 UDP sockets are supported by
 DatagramSocket
Java Socket Programming 8
JAVA TCP Sockets
 java.net.Socket
 Implements client sockets (also called just “sockets”).
 An endpoint for communication between two machines.
 Constructor and Methods
• Socket(String host, int port): Creates a stream socket and connects it to the specified port number
on the named host.
• InputStream getInputStream()
• OutputStream getOutputStream()
• close()
 java.net.ServerSocket
 Implements server sockets.
 Waits for requests to come in over the network.
 Performs some operation based on the request.
 Constructor and Methods
• ServerSocket(int port)
• Socket Accept(): Listens for a connection to be made to this socket and accepts it. This method
blocks until a connection is made.
Java Socket Programming 9
Sockets
Client socket, welcoming socket (passive) and connection socket (active)
Java Socket Programming 10
Socket Constructors
 Constructor creates a TCP connection to a
named TCP server.
 There are a number of constructors:
Socket(InetAddress server, int port);
Socket(InetAddress server, int port,
InetAddress local, int localport);
Socket(String hostname, int port);
Java Socket Programming 11
Socket Methods
void close();
InetAddress getInetAddress();
InetAddress getLocalAddress();
InputStream getInputStream();
OutputStream getOutputStream();
 Lots more (setting/getting socket options,
partial close, etc.)
Java Socket Programming 12
Socket I/O
 Socket I/O is based on the Java I/O support
 in the package java.io
 InputStream and OutputStream are abstract
classes
 common operations defined for all kinds of
InputStreams, OutputStreams…
Java Socket Programming 13
InputStream Basics
// reads some number of bytes and
// puts in buffer array b
int read(byte[] b);
// reads up to len bytes
int read(byte[] b, int off, int len);
Both methods can throw IOException.
Both return –1 on EOF.
Java Socket Programming 14
OutputStream Basics
// writes b.length bytes
void write(byte[] b);
// writes len bytes starting
// at offset off
void write(byte[] b, int off, int len);
Both methods can throw IOException.
Java Socket Programming 15
ServerSocket Class
(TCP Passive Socket)
 Constructors:
ServerSocket(int port);
ServerSocket(int port, int backlog);
ServerSocket(int port, int backlog,
InetAddress bindAddr);
Java Socket Programming 16
ServerSocket Methods
Socket accept();
void close();
InetAddress getInetAddress();
int getLocalPort();
throw IOException, SecurityException
Java Socket Programming 17
Socket programming with TCP
Example client-server app:
 client reads line from standard
input (inFromUser stream) ,
sends to server via socket
(outToServer stream)
 server reads line from socket
 server converts line to
uppercase, sends back to client
 client reads, prints modified
line from socket
(inFromServer stream)
outToServer
to network from network
inFromServer
inFromUser
keyboard monitor
Process
clientSocket
input
stream
input
stream
output
stream
TCP
socket
Input stream:
sequence of bytes
into process
output stream:
sequence of bytes
out of process
Client
process
client TCP
socket
Java Socket Programming 18
Client/server socket interaction: TCP
wait for incoming
connection request
connectionSocket =
welcomeSocket.accept()
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()
create socket,
connect to hostid, port=x
clientSocket =
Socket()
close
connectionSocket
read reply from
clientSocket
close
clientSocket
Server (running on hostid) Client
send request using
clientSocket
read request from
connectionSocket
write reply to
connectionSocket
TCP
connection setup
Java Socket Programming 19
TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("hostname", 6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
TCPClient.java
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + 'n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
Java Socket Programming 21
TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
TCPServer.java
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + 'n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
Java Socket Programming 23
Sample Echo Server
TCPEchoServer.java
Simple TCP Echo server.
Based on code from:
TCP/IP Sockets in Java
Java Socket Programming 24
UDP Sockets
 DatagramSocket class
 DatagramPacket class needed to specify the
payload
 incoming or outgoing
Java Socket Programming 25
Socket Programming with UDP
 UDP
 Connectionless and unreliable service.
 There isn’t an initial handshaking phase.
 Doesn’t have a pipe.
 transmitted data may be received out of order, or lost
 Socket Programming with UDP
 No need for a welcoming socket.
 No streams are attached to the sockets.
 the sending hosts creates “packets” by attaching the IP destination
address and port number to each batch of bytes.
 The receiving process must unravel to received packet to obtain the
packet’s information bytes.
Java Socket Programming 26
JAVA UDP Sockets
 In Package java.net
 java.net.DatagramSocket
• A socket for sending and receiving datagram packets.
• Constructor and Methods
– DatagramSocket(int port): Constructs a datagram
socket and binds it to the specified port on the local
host machine.
– void receive( DatagramPacket p)
– void send( DatagramPacket p)
– void close()
Java Socket Programming 27
DatagramSocket Constructors
DatagramSocket();
DatagramSocket(int port);
DatagramSocket(int port, InetAddress a);
All can throw SocketException or
SecurityException
Java Socket Programming 28
Datagram Methods
void connect(InetAddress, int port);
void close();
void receive(DatagramPacket p);
void send(DatagramPacket p);
Lots more!
Java Socket Programming 29
Datagram Packet
 Contain the payload
 (a byte array
 Can also be used to specify the destination
address
 when not using connected mode UDP
Java Socket Programming 30
DatagramPacket Constructors
For receiving:
DatagramPacket( byte[] buf, int len);
For sending:
DatagramPacket( byte[] buf, int len
InetAddress a, int port);
Java Socket Programming 31
DatagramPacket methods
byte[] getData();
void setData(byte[] buf);
void setAddress(InetAddress a);
void setPort(int port);
InetAddress getAddress();
int getPort();
Java Socket Programming 32
Example: Java client (UDP)
sendPacket
to network from network
receivePacket
inFromUser
keyboard monitor
Process
clientSocket
UDP
packet
input
stream
UDP
packet
UDP
socket
Output: sends
packet (TCP sent
“byte stream”)
Input: receives
packet (TCP
received “byte
stream”)
Client
process
client UDP
socket
Java Socket Programming 33
Client/server socket interaction: UDP
close
clientSocket
Server (running on hostid)
read reply from
clientSocket
create socket,
clientSocket =
DatagramSocket()
Client
Create, address (hostid, port=x,
send datagram request
using clientSocket
create socket,
port=x, for
incoming request:
serverSocket =
DatagramSocket()
read request from
serverSocket
write reply to
serverSocket
specifying client
host address,
port umber
Java Socket Programming 34
UDPClient.java
import java.io.*;
import java.net.*;
class UDPClient {
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress =
InetAddress.getByName("hostname");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
UDPClient.java
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length,
IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence =
new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
Java Socket Programming 36
UDPServer.java
import java.io.*;
import java.net.*;
class UDPServer {
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new
DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
UDPServer.java
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
Java Socket Programming 38
Sample UDP code
UDPEchoServer.java
Simple UDP Echo server.
Test using nc as the client (netcat):
> nc –u hostname port
Java Socket Programming 39
Socket functional calls
 socket (): Create a socket
 bind(): bind a socket to a local IP address and port #
 listen(): passively waiting for connections
 connect(): initiating connection to another socket
 accept(): accept a new connection
 Write(): write data to a socket
 Read(): read data from a socket
 sendto(): send a datagram to another UDP socket
 recvfrom(): read a datagram from a UDP socket
 close(): close a socket (tear down the connection)
Java Socket Programming 40
Java URL Class
 Represents a Uniform Resource Locator
 scheme (protocol)
 hostname
 port
 path
 query string
Java Socket Programming 41
Parsing
 You can use a URL object as a parser:
URL u = new URL(“http://www.cs.unr.edu/”);
System.out.println(“Proto:” + u.getProtocol());
System.out.println(“File:” + u.getFile());
Java Socket Programming 42
URL construction
 You can also build a URL by setting each part individually:
URL u = new URL(“http”,
www.cs.unr.edu,80,”/~mgunes/”);
System.out.println(“URL:” + u.toExternalForm());
System.out.println(“URL: “ + u);
Java Socket Programming 43
Retrieving URL contents
 URL objects can retrieve the documents they refer
to!
 actually this depends on the protocol part of the URL.
 HTTP is supported
 File is supported (“file://c:foo.html”)
 You can get “Protocol Handlers” for other protocols.
 There are a number of ways to do this:
Object getContent();
InputStream openStream();
URLConnection openConnection();
Java Socket Programming 44
Getting Header Information
 There are methods that return information extracted
from response headers:
String getContentType();
String getContentLength();
long getLastModified();
Java Socket Programming 45
URLConnection
 Represents the connection (not the URL itself).
 More control than URL
 can write to the connection (send POST data).
 can set request headers.
 Closely tied to HTTP
Java Socket Programming 46
For more detail contact us

More Related Content

Similar to Networking.ppt(client/server, socket) uses in program

Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.comphanleson
 
Sockets in nach0s
Sockets in nach0sSockets in nach0s
Sockets in nach0snaniix21_3
 
Java client socket-20070327
Java client socket-20070327Java client socket-20070327
Java client socket-20070327Tsu-Fen Han
 
Socket programming
Socket programmingSocket programming
Socket programmingharsh_bca06
 
Socket programming
Socket programmingSocket programming
Socket programmingharsh_bca06
 
Java networking programs - theory
Java networking programs - theoryJava networking programs - theory
Java networking programs - theoryMukesh Tekwani
 
5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptxEliasPetros
 
session6-Network Programming.pptx
session6-Network Programming.pptxsession6-Network Programming.pptx
session6-Network Programming.pptxSrinivasanG52
 
Networks lab
Networks labNetworks lab
Networks labsvijiiii
 
Networks lab
Networks labNetworks lab
Networks labsvijiiii
 

Similar to Networking.ppt(client/server, socket) uses in program (20)

Java socket presentation
Java socket presentation Java socket presentation
Java socket presentation
 
Sockets
SocketsSockets
Sockets
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 
Sockets in nach0s
Sockets in nach0sSockets in nach0s
Sockets in nach0s
 
Java client socket-20070327
Java client socket-20070327Java client socket-20070327
Java client socket-20070327
 
Client server project
Client server projectClient server project
Client server project
 
A.java
A.javaA.java
A.java
 
28 networking
28  networking28  networking
28 networking
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Java networking programs - theory
Java networking programs - theoryJava networking programs - theory
Java networking programs - theory
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 
5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptx
 
session6-Network Programming.pptx
session6-Network Programming.pptxsession6-Network Programming.pptx
session6-Network Programming.pptx
 
T2
T2T2
T2
 
#2 (UDP)
#2 (UDP)#2 (UDP)
#2 (UDP)
 
Networks lab
Networks labNetworks lab
Networks lab
 
Networks lab
Networks labNetworks lab
Networks lab
 

Recently uploaded

HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixingviprabot1
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 

Recently uploaded (20)

POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixing
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 

Networking.ppt(client/server, socket) uses in program

  • 1. C603.1 Design GUI using AWT and Swing . C603.2 Develop program using event handling. C603.3 Use network concepts (client/server, socket) in the program. C603.4 Develop program using JDBC connectivity to access data from database and execute different queries to get required result. C603.5 Develop web based program using servlet and JSP Course Outcomes of Advanced Java Programming AJP (17625, C603) Visit for more Learning Resources
  • 3. Java Sockets Programming  The package java.net provides support for sockets programming (and more).  Typically you import everything defined in this package with: import java.net.*; Java Socket Programming 3
  • 5. InetAddress class  static methods you can use to create new InetAddress objects.  getByName(String host)  getAllByName(String host)  getLocalHost() InetAddress x = InetAddress.getByName( “cse.unr.edu”);  Throws UnknownHostException Java Socket Programming 5
  • 6. Sample Code: Lookup.java  Uses InetAddress class to lookup hostnames found on command line. > java Lookup cse.unr.edu www.yahoo.com cse.unr.edu:134.197.40.9 www.yahoo.com:209.131.36.158 Java Socket Programming 6
  • 7. try { InetAddress a = InetAddress.getByName(hostname); System.out.println(hostname + ":" + a.getHostAddress()); } catch (UnknownHostException e) { System.out.println("No address found for " + hostname); } Java Socket Programming
  • 8. Socket class  Corresponds to active TCP sockets only!  client sockets  socket returned by accept();  Passive sockets are supported by a different class:  ServerSocket  UDP sockets are supported by  DatagramSocket Java Socket Programming 8
  • 9. JAVA TCP Sockets  java.net.Socket  Implements client sockets (also called just “sockets”).  An endpoint for communication between two machines.  Constructor and Methods • Socket(String host, int port): Creates a stream socket and connects it to the specified port number on the named host. • InputStream getInputStream() • OutputStream getOutputStream() • close()  java.net.ServerSocket  Implements server sockets.  Waits for requests to come in over the network.  Performs some operation based on the request.  Constructor and Methods • ServerSocket(int port) • Socket Accept(): Listens for a connection to be made to this socket and accepts it. This method blocks until a connection is made. Java Socket Programming 9
  • 10. Sockets Client socket, welcoming socket (passive) and connection socket (active) Java Socket Programming 10
  • 11. Socket Constructors  Constructor creates a TCP connection to a named TCP server.  There are a number of constructors: Socket(InetAddress server, int port); Socket(InetAddress server, int port, InetAddress local, int localport); Socket(String hostname, int port); Java Socket Programming 11
  • 12. Socket Methods void close(); InetAddress getInetAddress(); InetAddress getLocalAddress(); InputStream getInputStream(); OutputStream getOutputStream();  Lots more (setting/getting socket options, partial close, etc.) Java Socket Programming 12
  • 13. Socket I/O  Socket I/O is based on the Java I/O support  in the package java.io  InputStream and OutputStream are abstract classes  common operations defined for all kinds of InputStreams, OutputStreams… Java Socket Programming 13
  • 14. InputStream Basics // reads some number of bytes and // puts in buffer array b int read(byte[] b); // reads up to len bytes int read(byte[] b, int off, int len); Both methods can throw IOException. Both return –1 on EOF. Java Socket Programming 14
  • 15. OutputStream Basics // writes b.length bytes void write(byte[] b); // writes len bytes starting // at offset off void write(byte[] b, int off, int len); Both methods can throw IOException. Java Socket Programming 15
  • 16. ServerSocket Class (TCP Passive Socket)  Constructors: ServerSocket(int port); ServerSocket(int port, int backlog); ServerSocket(int port, int backlog, InetAddress bindAddr); Java Socket Programming 16
  • 17. ServerSocket Methods Socket accept(); void close(); InetAddress getInetAddress(); int getLocalPort(); throw IOException, SecurityException Java Socket Programming 17
  • 18. Socket programming with TCP Example client-server app:  client reads line from standard input (inFromUser stream) , sends to server via socket (outToServer stream)  server reads line from socket  server converts line to uppercase, sends back to client  client reads, prints modified line from socket (inFromServer stream) outToServer to network from network inFromServer inFromUser keyboard monitor Process clientSocket input stream input stream output stream TCP socket Input stream: sequence of bytes into process output stream: sequence of bytes out of process Client process client TCP socket Java Socket Programming 18
  • 19. Client/server socket interaction: TCP wait for incoming connection request connectionSocket = welcomeSocket.accept() create socket, port=x, for incoming request: welcomeSocket = ServerSocket() create socket, connect to hostid, port=x clientSocket = Socket() close connectionSocket read reply from clientSocket close clientSocket Server (running on hostid) Client send request using clientSocket read request from connectionSocket write reply to connectionSocket TCP connection setup Java Socket Programming 19
  • 20. TCPClient.java import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("hostname", 6789); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  • 21. TCPClient.java BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + 'n'); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } } Java Socket Programming 21
  • 22. TCPServer.java import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(6789); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
  • 23. TCPServer.java DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + 'n'; outToClient.writeBytes(capitalizedSentence); } } } Java Socket Programming 23
  • 24. Sample Echo Server TCPEchoServer.java Simple TCP Echo server. Based on code from: TCP/IP Sockets in Java Java Socket Programming 24
  • 25. UDP Sockets  DatagramSocket class  DatagramPacket class needed to specify the payload  incoming or outgoing Java Socket Programming 25
  • 26. Socket Programming with UDP  UDP  Connectionless and unreliable service.  There isn’t an initial handshaking phase.  Doesn’t have a pipe.  transmitted data may be received out of order, or lost  Socket Programming with UDP  No need for a welcoming socket.  No streams are attached to the sockets.  the sending hosts creates “packets” by attaching the IP destination address and port number to each batch of bytes.  The receiving process must unravel to received packet to obtain the packet’s information bytes. Java Socket Programming 26
  • 27. JAVA UDP Sockets  In Package java.net  java.net.DatagramSocket • A socket for sending and receiving datagram packets. • Constructor and Methods – DatagramSocket(int port): Constructs a datagram socket and binds it to the specified port on the local host machine. – void receive( DatagramPacket p) – void send( DatagramPacket p) – void close() Java Socket Programming 27
  • 28. DatagramSocket Constructors DatagramSocket(); DatagramSocket(int port); DatagramSocket(int port, InetAddress a); All can throw SocketException or SecurityException Java Socket Programming 28
  • 29. Datagram Methods void connect(InetAddress, int port); void close(); void receive(DatagramPacket p); void send(DatagramPacket p); Lots more! Java Socket Programming 29
  • 30. Datagram Packet  Contain the payload  (a byte array  Can also be used to specify the destination address  when not using connected mode UDP Java Socket Programming 30
  • 31. DatagramPacket Constructors For receiving: DatagramPacket( byte[] buf, int len); For sending: DatagramPacket( byte[] buf, int len InetAddress a, int port); Java Socket Programming 31
  • 32. DatagramPacket methods byte[] getData(); void setData(byte[] buf); void setAddress(InetAddress a); void setPort(int port); InetAddress getAddress(); int getPort(); Java Socket Programming 32
  • 33. Example: Java client (UDP) sendPacket to network from network receivePacket inFromUser keyboard monitor Process clientSocket UDP packet input stream UDP packet UDP socket Output: sends packet (TCP sent “byte stream”) Input: receives packet (TCP received “byte stream”) Client process client UDP socket Java Socket Programming 33
  • 34. Client/server socket interaction: UDP close clientSocket Server (running on hostid) read reply from clientSocket create socket, clientSocket = DatagramSocket() Client Create, address (hostid, port=x, send datagram request using clientSocket create socket, port=x, for incoming request: serverSocket = DatagramSocket() read request from serverSocket write reply to serverSocket specifying client host address, port umber Java Socket Programming 34
  • 35. UDPClient.java import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes();
  • 36. UDPClient.java DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } } Java Socket Programming 36
  • 37. UDPServer.java import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData());
  • 38. UDPServer.java InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } } } Java Socket Programming 38
  • 39. Sample UDP code UDPEchoServer.java Simple UDP Echo server. Test using nc as the client (netcat): > nc –u hostname port Java Socket Programming 39
  • 40. Socket functional calls  socket (): Create a socket  bind(): bind a socket to a local IP address and port #  listen(): passively waiting for connections  connect(): initiating connection to another socket  accept(): accept a new connection  Write(): write data to a socket  Read(): read data from a socket  sendto(): send a datagram to another UDP socket  recvfrom(): read a datagram from a UDP socket  close(): close a socket (tear down the connection) Java Socket Programming 40
  • 41. Java URL Class  Represents a Uniform Resource Locator  scheme (protocol)  hostname  port  path  query string Java Socket Programming 41
  • 42. Parsing  You can use a URL object as a parser: URL u = new URL(“http://www.cs.unr.edu/”); System.out.println(“Proto:” + u.getProtocol()); System.out.println(“File:” + u.getFile()); Java Socket Programming 42
  • 43. URL construction  You can also build a URL by setting each part individually: URL u = new URL(“http”, www.cs.unr.edu,80,”/~mgunes/”); System.out.println(“URL:” + u.toExternalForm()); System.out.println(“URL: “ + u); Java Socket Programming 43
  • 44. Retrieving URL contents  URL objects can retrieve the documents they refer to!  actually this depends on the protocol part of the URL.  HTTP is supported  File is supported (“file://c:foo.html”)  You can get “Protocol Handlers” for other protocols.  There are a number of ways to do this: Object getContent(); InputStream openStream(); URLConnection openConnection(); Java Socket Programming 44
  • 45. Getting Header Information  There are methods that return information extracted from response headers: String getContentType(); String getContentLength(); long getLastModified(); Java Socket Programming 45
  • 46. URLConnection  Represents the connection (not the URL itself).  More control than URL  can write to the connection (send POST data).  can set request headers.  Closely tied to HTTP Java Socket Programming 46 For more detail contact us