SlideShare a Scribd company logo
1 of 34
Socket Programming in JAVA
Mohammed Abdalla Youssif
Teaching Assistant
Faculty of Computers & Information
Systems - Beni Suef University
Mobile: +20-1001656577
1
OUTLINE
• BACKGROUND
• What Is a Socket?
• Ports
• Two essential types of sockets
• Network Exceptions
• Classes in Network programming
• Set up input and output streams
• TCP Sockets
• Socket Client
• Socket Server
• How do I create an input stream?
• How do I close sockets?
2
BACKGROUND
• The communication that occurs between the
client and the server must be reliable.
• reliable means That is, no data can be
dropped and must arrive on the client side in
the same order in which the server sent it.
• TCP provides a reliable, point-to-point
communication channel that client-server
applications.
3
What Is a Socket?
• A socket is one end-point of a two-way
communication link between two programs running
on the network.
• Socket classes are used to represent the connection
between a client program and a server program.
• The java.net package provides two classes :
– Socket --that implement the client side of the
connection
– ServerSocket implement server side of the
connection, respectively.
•
4
What Is a Socket?
• A socket is bound to a port number so that the TCP
layer can identify the application that data is
destined to be sent to.
• Normally, a server runs on a specific computer and
has a socket that is bound to a specific port number.
• The server just waits, listening to the socket for a
client to make a connection request.
• On the client-side: The client knows the hostname of
the machine on which the server is running and the
port number on which the server is listening.
•
5
What Is a Socket?
• To make a connection request, the client tries to
connect with the server on the server's machine and
port.
• The client also needs to identify itself to the server
so it binds to a local port number that it will use
during this connection.
•
6
What Is a Socket?
• If everything goes well, the server accepts the
connection.
• Upon acceptance, the server gets a new socket
bound to the same local port and also has its remote
endpoint set to the address and port of the client.
• On the client side, if the connection is accepted, a
socket is successfully created and the client can use
the socket to communicate with the server.
•
7
What Is a Socket?
• The client and server can now communicate by
writing to or reading from their sockets.
• An endpoint is a combination of an IP address and a
port number.
• Every TCP connection can be uniquely identified by
its two endpoints.
• That way you can have multiple connections
between your host and the server.
•
8
Ports
Port 0
Port 1
Port 65535
• Each host has 65,536
ports
• Some ports are
reserved for specific
apps
– 20,21: FTP
– 23: Telnet
– 80: HTTP
 A socket provides an interface
to send data to/from the
network through a port
What is a Port? A Port Number?
• Port numbers are used to identify services on
a host
• – Port numbers can be:
• well-known
• dynamic or private
• Clients usually use dynamic ports
1
Two essential types of sockets
• STREAM
– a.k.a. TCP
– reliable delivery
– in-order guaranteed
– connection-oriented
– bidirectional
Service
Request
Service
Request
Service
Request
Limit on Number of
Processes that can
successfully request
service at a time
Process
Request
Serviced
2
Connect
3
“Listen” for
service
requests
• DATAGRAM
– a.k.a. UDP
– unreliable delivery; data can be
lost, although this is unusual
– no order guarantees
– no notion of “connection” – app
indicates dest. for each packet
– can send or receive
Two essential types of sockets
Process
Process
Send to recipient
Receive from Sender
Indeterminate
path
TCP Vs. UDP Socket programming
• Sockets are a protocol independent method of
creating a connection between processes.
Sockets can be either
• Connection based or Connectionless: Is a
connection established before communication or
does each packet describe the destination?
• Packet based or Streams based: Are there
message boundaries or is it one stream?
• Reliable or Unreliable: Can messages be lost,
duplicated, reordered, or corrupted?
TCP Vs. UDP Socket programming
• SOCK_STREAM
– TCP
– connection-oriented
– reliable delivery
– in-order guaranteed
– bidirectional
Two essential types of sockets
• SOCK_DGRAM
– UDP
– no notion of “connection” – app
– indicates dest. for each packet
– unreliable delivery
– no order guarantees
– can send or receive
UDP Connection
TCP
• Unlike UDP, TCP is a connection-oriented protocol. This
means that before the client and server can start to send
data to each other, they first need to handshake and
establish a TCP connection.
• When creating the TCP connection, we associate with it the
client socket address (IP address and port number) and the
server socket address (IP address and port number).
• With the TCP connection established, when one side wants
to send data to the other side, it just drops the data into
the TCP connection via its socket. This is different from
UDP, for which the server must attach a destination
address to the packet before dropping it into the socket.
TCP Connection
Network Exceptions in Java
• BindException
• ConnectException
• MalformedURLException
• NoRouteToHostException
• ProtocolException
• SocketException
• UnknownHostException
• UnknownServiceException
Classes in java.net
• The core package java.net contains a number of classes
that allow programmers to carry out network
programming
– ContentHandler
– DatagramPacket
– DatagramSocket
– DatagramSocketImplHttpURLConnection
– InetAddress
– MulticastSocket
– ServerSocket
– Socket
– SocketImpl
– URL
– URLConnection
– URLEncoder
– URLStreamHandler
The InetAddress Class
• Handles Internet addresses both as host names and as IP
addresses
• Static Method getByName returns the IP address of a
specified host name as an InetAddress object
• Methods for address/name conversion:
public static InetAddress getByName(String host) throws UnknownHostException
public static InetAddress[] getAllByName(String host) throws UnknownHostException
public static InetAddress getLocalHost() throws UnknownHostException
public boolean isMulticastAddress()
public String getHostName()
public byte[] getAddress()
public String getHostAddress()
public int hashCode()
public boolean equals(Object obj)
public String toString()
The Java.net.Socket Class
• Connection is accomplished via construction.
–Each Socket object is associated with exactly
one remote host.
• Sending and receiving data is accomplished
with output and input streams.
• There are methods to get an input stream for
a socket and an output stream for the socket.
The Java.net.ServerSocket Class
• The java.net.ServerSocket class represents a server socket.
• It is constructed on a particular port.
• Then it calls accept() to listen for incoming connections.
– accept() blocks until a connection is detected.
– Then accept() returns a java.net.Socket object that is used to perform
the actual communication with the client.
• the “plug”
– backlog is the maximum size of the queue of connection requests
public ServerSocket(int port) throws IOException
public ServerSocket(int port, int backlog) throws IOException
public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException
public Socket accept() throws IOException
public void close() throws IOException
Set up input and output streams
• Once a socket has connected you send data to
the server via an output stream. You receive
data from the server via an input stream.
• Methods getInputStream and getOutputStream
of class Socket:
BufferedReader in =
new BufferedReader(
new
InputStreamReader(link.getInputStream()));
PrintWriter out =
new PrintWriter(link.getOutputStream(),true);
TCP Sockets
Example: SocketClient.java
CLIENT:
1. Establish a connection to the server
Socket link =
new Socket(<server>,<port>);
2. Set up input and output streams
3. Send and receive data
4. Close the connection
Socket Client
•
• Where Machine name is the machine you are
trying to open a connection to, and
PortNumber is the port (a number) on which
the server you are trying to connect to is
running.
TCP Sockets
Example: SocketServer.java
SERVER:
1. Create a ServerSocket object
ServerSocket servSocket = new ServerSocket(1234);
2. Put the server into a waiting state
Socket link = servSocket.accept();
3. Set up input and output streams
• use thread to serve this client via link
4. Send and receive data
out.println(awaiting data…);
String input = in.readLine();
5. Close the connection
link.close()
Socket Server
• If you are programming a server, then this is
how you open a socket:
•
Socket Server
• When implementing a server you also need to
create a socket object from the ServerSocket
in order to listen for and accept connections
from clients.
•
How do I create an input
stream?
• On the client side, you can use the
DataInputStream class to create an input
stream to receive response from the server:
•
How do I close sockets?
• You should always close the output and input
stream before you close the socket.
• On the client side:
•
How do I close sockets?
• On the server side:
•
Questions
33
REFERNCES
1. Comparison between TCP sockets and UDP Sockets
http://www.cyberciti.biz/faq/key-differences-between-tcp-
and-udp-protocols/
34

More Related Content

What's hot (20)

Network software
Network softwareNetwork software
Network software
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 
Transport Layer Services : Multiplexing And Demultiplexing
Transport Layer Services : Multiplexing And DemultiplexingTransport Layer Services : Multiplexing And Demultiplexing
Transport Layer Services : Multiplexing And Demultiplexing
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Routing ppt
Routing pptRouting ppt
Routing ppt
 
Applets
AppletsApplets
Applets
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Computer Network - Network Layer
Computer Network - Network LayerComputer Network - Network Layer
Computer Network - Network Layer
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Computer network switching
Computer network switchingComputer network switching
Computer network switching
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Transmission Control Protocol (TCP)
Transmission Control Protocol (TCP)Transmission Control Protocol (TCP)
Transmission Control Protocol (TCP)
 
Datagrams
DatagramsDatagrams
Datagrams
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Data management with ado
Data management with adoData management with ado
Data management with ado
 

Similar to Java socket programming

Networking.pptx
Networking.pptxNetworking.pptx
Networking.pptxEsubesisay
 
5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptxEliasPetros
 
OOP Lecture 24-Network Programming-Part1.pptx
OOP Lecture 24-Network Programming-Part1.pptxOOP Lecture 24-Network Programming-Part1.pptx
OOP Lecture 24-Network Programming-Part1.pptxTanzila Kehkashan
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAMaulik Borsaniya
 
Socket programming
Socket programmingSocket programming
Socket programmingUjjwal Kumar
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat applicationPiyush Rawat
 
chapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhjchapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhjAmitDeshai
 
Java_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptJava_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptssuserec53e73
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using CAjit Nayak
 
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
 
Byte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxByte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxRockyBhai46825
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat applicationSamsil Arefin
 
Java_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptJava_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptssuserec53e73
 

Similar to Java socket programming (20)

Chapter 4--converted.pptx
Chapter 4--converted.pptxChapter 4--converted.pptx
Chapter 4--converted.pptx
 
Networking.pptx
Networking.pptxNetworking.pptx
Networking.pptx
 
5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptx
 
OOP Lecture 24-Network Programming-Part1.pptx
OOP Lecture 24-Network Programming-Part1.pptxOOP Lecture 24-Network Programming-Part1.pptx
OOP Lecture 24-Network Programming-Part1.pptx
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 
chapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhjchapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhj
 
Java_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptJava_Socket_Programming (2).ppt
Java_Socket_Programming (2).ppt
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using C
 
java networking
 java networking java networking
java networking
 
17-Networking.pdf
17-Networking.pdf17-Networking.pdf
17-Networking.pdf
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programming
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Networking in python by Rj
Networking in python by RjNetworking in python by Rj
Networking in python by Rj
 
28 networking
28  networking28  networking
28 networking
 
Socket & Server Socket
Socket & Server SocketSocket & Server Socket
Socket & Server Socket
 
Byte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxByte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptx
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 
Java_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptJava_Socket_Programming (2).ppt
Java_Socket_Programming (2).ppt
 

Recently uploaded

办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 

Recently uploaded (20)

办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 

Java socket programming

  • 1. Socket Programming in JAVA Mohammed Abdalla Youssif Teaching Assistant Faculty of Computers & Information Systems - Beni Suef University Mobile: +20-1001656577 1
  • 2. OUTLINE • BACKGROUND • What Is a Socket? • Ports • Two essential types of sockets • Network Exceptions • Classes in Network programming • Set up input and output streams • TCP Sockets • Socket Client • Socket Server • How do I create an input stream? • How do I close sockets? 2
  • 3. BACKGROUND • The communication that occurs between the client and the server must be reliable. • reliable means That is, no data can be dropped and must arrive on the client side in the same order in which the server sent it. • TCP provides a reliable, point-to-point communication channel that client-server applications. 3
  • 4. What Is a Socket? • A socket is one end-point of a two-way communication link between two programs running on the network. • Socket classes are used to represent the connection between a client program and a server program. • The java.net package provides two classes : – Socket --that implement the client side of the connection – ServerSocket implement server side of the connection, respectively. • 4
  • 5. What Is a Socket? • A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. • Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. • The server just waits, listening to the socket for a client to make a connection request. • On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. • 5
  • 6. What Is a Socket? • To make a connection request, the client tries to connect with the server on the server's machine and port. • The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. • 6
  • 7. What Is a Socket? • If everything goes well, the server accepts the connection. • Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. • On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. • 7
  • 8. What Is a Socket? • The client and server can now communicate by writing to or reading from their sockets. • An endpoint is a combination of an IP address and a port number. • Every TCP connection can be uniquely identified by its two endpoints. • That way you can have multiple connections between your host and the server. • 8
  • 9. Ports Port 0 Port 1 Port 65535 • Each host has 65,536 ports • Some ports are reserved for specific apps – 20,21: FTP – 23: Telnet – 80: HTTP  A socket provides an interface to send data to/from the network through a port
  • 10. What is a Port? A Port Number? • Port numbers are used to identify services on a host • – Port numbers can be: • well-known • dynamic or private • Clients usually use dynamic ports
  • 11. 1 Two essential types of sockets • STREAM – a.k.a. TCP – reliable delivery – in-order guaranteed – connection-oriented – bidirectional Service Request Service Request Service Request Limit on Number of Processes that can successfully request service at a time Process Request Serviced 2 Connect 3 “Listen” for service requests
  • 12. • DATAGRAM – a.k.a. UDP – unreliable delivery; data can be lost, although this is unusual – no order guarantees – no notion of “connection” – app indicates dest. for each packet – can send or receive Two essential types of sockets Process Process Send to recipient Receive from Sender Indeterminate path
  • 13. TCP Vs. UDP Socket programming • Sockets are a protocol independent method of creating a connection between processes. Sockets can be either • Connection based or Connectionless: Is a connection established before communication or does each packet describe the destination? • Packet based or Streams based: Are there message boundaries or is it one stream? • Reliable or Unreliable: Can messages be lost, duplicated, reordered, or corrupted?
  • 14. TCP Vs. UDP Socket programming • SOCK_STREAM – TCP – connection-oriented – reliable delivery – in-order guaranteed – bidirectional
  • 15. Two essential types of sockets • SOCK_DGRAM – UDP – no notion of “connection” – app – indicates dest. for each packet – unreliable delivery – no order guarantees – can send or receive
  • 17. TCP • Unlike UDP, TCP is a connection-oriented protocol. This means that before the client and server can start to send data to each other, they first need to handshake and establish a TCP connection. • When creating the TCP connection, we associate with it the client socket address (IP address and port number) and the server socket address (IP address and port number). • With the TCP connection established, when one side wants to send data to the other side, it just drops the data into the TCP connection via its socket. This is different from UDP, for which the server must attach a destination address to the packet before dropping it into the socket.
  • 19. Network Exceptions in Java • BindException • ConnectException • MalformedURLException • NoRouteToHostException • ProtocolException • SocketException • UnknownHostException • UnknownServiceException
  • 20. Classes in java.net • The core package java.net contains a number of classes that allow programmers to carry out network programming – ContentHandler – DatagramPacket – DatagramSocket – DatagramSocketImplHttpURLConnection – InetAddress – MulticastSocket – ServerSocket – Socket – SocketImpl – URL – URLConnection – URLEncoder – URLStreamHandler
  • 21. The InetAddress Class • Handles Internet addresses both as host names and as IP addresses • Static Method getByName returns the IP address of a specified host name as an InetAddress object • Methods for address/name conversion: public static InetAddress getByName(String host) throws UnknownHostException public static InetAddress[] getAllByName(String host) throws UnknownHostException public static InetAddress getLocalHost() throws UnknownHostException public boolean isMulticastAddress() public String getHostName() public byte[] getAddress() public String getHostAddress() public int hashCode() public boolean equals(Object obj) public String toString()
  • 22. The Java.net.Socket Class • Connection is accomplished via construction. –Each Socket object is associated with exactly one remote host. • Sending and receiving data is accomplished with output and input streams. • There are methods to get an input stream for a socket and an output stream for the socket.
  • 23. The Java.net.ServerSocket Class • The java.net.ServerSocket class represents a server socket. • It is constructed on a particular port. • Then it calls accept() to listen for incoming connections. – accept() blocks until a connection is detected. – Then accept() returns a java.net.Socket object that is used to perform the actual communication with the client. • the “plug” – backlog is the maximum size of the queue of connection requests public ServerSocket(int port) throws IOException public ServerSocket(int port, int backlog) throws IOException public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException public Socket accept() throws IOException public void close() throws IOException
  • 24. Set up input and output streams • Once a socket has connected you send data to the server via an output stream. You receive data from the server via an input stream. • Methods getInputStream and getOutputStream of class Socket: BufferedReader in = new BufferedReader( new InputStreamReader(link.getInputStream())); PrintWriter out = new PrintWriter(link.getOutputStream(),true);
  • 25. TCP Sockets Example: SocketClient.java CLIENT: 1. Establish a connection to the server Socket link = new Socket(<server>,<port>); 2. Set up input and output streams 3. Send and receive data 4. Close the connection
  • 26. Socket Client • • Where Machine name is the machine you are trying to open a connection to, and PortNumber is the port (a number) on which the server you are trying to connect to is running.
  • 27. TCP Sockets Example: SocketServer.java SERVER: 1. Create a ServerSocket object ServerSocket servSocket = new ServerSocket(1234); 2. Put the server into a waiting state Socket link = servSocket.accept(); 3. Set up input and output streams • use thread to serve this client via link 4. Send and receive data out.println(awaiting data…); String input = in.readLine(); 5. Close the connection link.close()
  • 28. Socket Server • If you are programming a server, then this is how you open a socket: •
  • 29. Socket Server • When implementing a server you also need to create a socket object from the ServerSocket in order to listen for and accept connections from clients. •
  • 30. How do I create an input stream? • On the client side, you can use the DataInputStream class to create an input stream to receive response from the server: •
  • 31. How do I close sockets? • You should always close the output and input stream before you close the socket. • On the client side: •
  • 32. How do I close sockets? • On the server side: •
  • 34. REFERNCES 1. Comparison between TCP sockets and UDP Sockets http://www.cyberciti.biz/faq/key-differences-between-tcp- and-udp-protocols/ 34

Editor's Notes

  1. To communicate over TCP, a client program and a server program establish a connection to one another. Each program binds a socket to its end of the connection. To communicate, the client and the server each reads from and writes to the socket bound to the connection.
  2. TCP is a reliable protocol which ensures that your packets reach their destination and is used in applications where all data must me trasfered accurately between parties. TCP requires both parties to negotiate a connection before data transfer can start and it is a resilient protocol since it will repeatedly resend a packet until that packet is received by the intended recipient. UDP is unreliable in a sense that it allows some packets to be lost in transit. Some applications of UDP are found in movie streaming where you can actually afford to lose a frame and not jeopardize movie quality. UDP does not need binding between the two parties and is often looked at as a light alternative to TCP.
  3. BindException-while attempting to bind a socket to a local address and port. Typically, the port is in use, or the requested local address could not be assigned. ConnectException--an error occurred while attempting to connect a socket to a remote address and port. Typically, the connection was refused remotely (e.g., no process is listening on the remote address/port). MalformedURLException--Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed. NoRouteToHostException--an error occurred while attempting to connect a socket to a remote address and port. Typically, the remote host cannot be reached because of an intervening firewall, or if an intermediate router is down. ProtocolException--Thrown to indicate that there is an error in the underlying protocol, such as a TCP error. SocketException--Thrown to indicate that there is an error creating or accessing a Socket. UnknownHostException--Thrown to indicate that the IP address of a host could not be determined.
  4. Note : When selecting a port number, you should note that port numbers between 0 and 1,023 are reserved for privileged users (that is, super user or root). These port numbers are reserved for standard services, such as email, FTP, and HTTP. When selecting a port number for your server, select one that is greater than 1,023!
  5. close input and output streams