SlideShare a Scribd company logo
1 of 18
SOCKETS
PROGRAMMAZIONE CONCORRENTE E DISTR.
Università degli Studi di Padova
Dipartimento di Matematica
Corso di Laurea in Informatica, A.A. 2015 – 2016
rcardin@math.unipd.it
Programmazione concorrente e distribuita
SUMMARY
 Introduction
 Sockets
 Client program
 Server program
 Protocol
2Riccardo Cardin
Programmazione concorrente e distribuita
INTRODUCTION
 Client-server applications
 The server provides some service
 The client uses the server provided by the server
 The communication must be reliable
 TCP provides a reliable, point-to-point
communication chanel over the Internet
 Each program binds a socket to its end of connection
 The communication is realized reading and writing
from and to the socket bound to the connection
3Riccardo Cardin
Programmazione concorrente e distribuita
INTRODUCTION
 A server runs on a specific host and has a socket
bound to a specific port
 The server waits, listening to the socket
 The client knows the hostname and port
number on which the server is listening
 Tries to randezvous with the server and binds a local
port number to use during connection
4Riccardo Cardindistribuita
Programmazione concorrente e distribuita
INTRODUCTION
5Riccardo Cardin
Programmazione concorrente e distribuita
SOCKETS
 An endpoint is a combination of an IP address and a
port number
 Every TCP connection is uniquely identified by its two
endpoints
 The class java.net.Socket implements the client
side of a two-way connection
 Sits on top of a platform-dependent implementation
 The class java.net.ServerSocket implements the
server side, that listen for connections to clients
6Riccardo Cardin
A socket is one endpoint of a two-way communication link between
two programs running on the network. 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.
Programmazione concorrente e distribuita
EXAMPLE: ECHO PROGRAM
 Let’s implement an example program
 The EchoClient writes to and reads from the socket
 Open a socket.
 Open an input stream and output stream to the socket.
 Read from and write to the stream according to the server's
protocol.
 Close the streams.
 Close the socket.
7Riccardo Cardin
The example program implements a client, EchoClient, that
connects to an echo server. The echo server receives data from its
client and echoes it back. The example EchoServer implements an
echo server. (Alternatively, the client can connect to any host that
supports the Echo Protocol.)
Programmazione concorrente e distribuita
CLIENT PROGRAM
 First of all, let’s open the socket
8Riccardo Cardin
// The client has the hostname and port of the server as inputs
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
// Open a socket connection to a host and a port number
Socket echoSocket = new Socket(hostName, portNumber);
// Build structures that write to the socket
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
// Build structures that read from the socket
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
// Read user input from console
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in))
)
Programmazione concorrente e distribuita
CLIENT PROGRAM
 The java.net.Socket class implements a
client socket
 A socket is binded to an hostname and a port during
building process
 Sockets implements AutoCloseable
 For reading from and writing to a socket we need
input and output streams
 The try-with-resources statement closes the streams and the
socket in the right order
 The server socket must be ready to accept incoming
connection
 Otherwise, the client socket will thrown an exception
9Riccardo Cardin
Programmazione concorrente e distribuita
CLIENT PROGRAM
 The protocol have to be implemented manually
 How the socket information are interpreted is
dependent from which stream is used to read from it
 A Ctrl+C is interpreted as an end-of-input
 The communication protocol is totally custom
 For example, talking to an HTTP server will be more
complicated
10Riccardo Cardin
String userInput;
// Reading user input until Ctrl+C is read
while ((userInput = stdIn.readLine()) != null) {
// Writing information to socket
out.println(userInput);
// Reading information to socket
System.out.println("echo: " + in.readLine());
}
Programmazione concorrente e distribuita
CLIENT PROGRAM
11Riccardo Cardin
Programmazione concorrente e distribuita
SERVER PROGRAM
 To the other end of endpoint a server is listening
to some incoming messages
12Riccardo Cardin
// The port number on which the server will listening
int portNumber = Integer.parseInt(args[0]);
try (
// A ServerSocket waits a client’s message on a specific port
ServerSocket serverSocket = new ServerSocket(portNumber);
// Once a message has arrived, a socket is created to manage
// the connection with the client
Socket clientSocket = serverSocket.accept();
// Structure to write to the socket
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
// Structure to read from the socket
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
)
Programmazione concorrente e distribuita
SERVER PROGRAM
13Riccardo Cardin
Programmazione concorrente e distribuita
SERVER PROGRAM
 Using java.net.ServerSocket a server can
accept a connection from a client
 The accept method waits until a client request a
connection to the host and port of the server
 A Socket is created on the same port, to managed the
connection with the new client
 It is possible to have a «multiple client» server
 For each new connection, create a dedicated Thread
 The communication is manage using streams
14Riccardo Cardin
while (true) {
// accept a connection
// create a thread to deal with the client
}
Programmazione concorrente e distribuita
SERVER PROGRAM
15Riccardo Cardin
Programmazione concorrente e distribuita
PROTOCOL
 Who speaks first?
 The problem with socket communication is that it is a
low level type of communication
 The protocol is custom for each type of
implementation
 Usually a dedicated class is used to implement the
protocol
 Given a received message, it returns the next action to do
 Server port is part of the protocol
 The server MUST be already listening for incoming
connection when clients try to communicate with it
 Only the accept method of ServerSocket is blocking
16Riccardo Cardin
Programmazione concorrente e distribuita
EXAMPLES
17Riccardo Cardin
https://github.com/rcardin/pcd-snippets
Programmazione concorrente e distribuita
REFERENCES
 Lesson: All About Socket
https://docs.oracle.com/javase/tutorial/networking/sockets/
 Echo Protocol http://tools.ietf.org/html/rfc862
 Does the port change when a TCP connection is accepted by a
server? http://stackoverflow.com/questions/2997754/does-the-
port-change-when-a-tcp-connection-is-accepted-by-a-server
18Riccardo Cardin

More Related Content

What's hot

Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49
myrajendra
 

What's hot (20)

Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
graphics programming in java
graphics programming in javagraphics programming in java
graphics programming in java
 
JNDI
JNDIJNDI
JNDI
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
 
Graphics programming in Java
Graphics programming in JavaGraphics programming in Java
Graphics programming in Java
 
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
What is Multithreading In Python | Python Multithreading Tutorial | EdurekaWhat is Multithreading In Python | Python Multithreading Tutorial | Edureka
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
gRPC Overview
gRPC OverviewgRPC Overview
gRPC Overview
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Notification android
Notification androidNotification android
Notification android
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
PHP - Introduction to File Handling with PHP
PHP -  Introduction to  File Handling with PHPPHP -  Introduction to  File Handling with PHP
PHP - Introduction to File Handling with PHP
 
URL Class in JAVA
URL Class in JAVAURL Class in JAVA
URL Class in JAVA
 

Viewers also liked

Viewers also liked (20)

Diagrammi di Sequenza
Diagrammi di SequenzaDiagrammi di Sequenza
Diagrammi di Sequenza
 
Java - Concurrent programming - Thread's advanced concepts
Java - Concurrent programming - Thread's advanced conceptsJava - Concurrent programming - Thread's advanced concepts
Java - Concurrent programming - Thread's advanced concepts
 
Java Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and LoggingJava Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and Logging
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
 
Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics Programming
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala
 
Design pattern architetturali Model View Controller, MVP e MVVM
Design pattern architetturali   Model View Controller, MVP e MVVMDesign pattern architetturali   Model View Controller, MVP e MVVM
Design pattern architetturali Model View Controller, MVP e MVVM
 
Java- Concurrent programming - Synchronization (part 1)
Java- Concurrent programming - Synchronization (part 1)Java- Concurrent programming - Synchronization (part 1)
Java- Concurrent programming - Synchronization (part 1)
 
Java- Concurrent programming - Synchronization (part 2)
Java- Concurrent programming - Synchronization (part 2)Java- Concurrent programming - Synchronization (part 2)
Java- Concurrent programming - Synchronization (part 2)
 
Design Pattern Strutturali
Design Pattern StrutturaliDesign Pattern Strutturali
Design Pattern Strutturali
 
Introduzione ai Design Pattern
Introduzione ai Design PatternIntroduzione ai Design Pattern
Introduzione ai Design Pattern
 
Diagrammi delle Classi
Diagrammi delle ClassiDiagrammi delle Classi
Diagrammi delle Classi
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
 
Java - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basicsJava - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basics
 
Presto updates to 0.178
Presto updates to 0.178Presto updates to 0.178
Presto updates to 0.178
 
Errori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei RequisitiErrori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei Requisiti
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patterns
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java Programmers
 
Java - Remote method invocation
Java - Remote method invocationJava - Remote method invocation
Java - Remote method invocation
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented Design
 

Similar to Java - Sockets

Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
kacie8xcheco
 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
hanneloremccaffery
 

Similar to Java - Sockets (20)

Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
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
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Networking
NetworkingNetworking
Networking
 
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
 
Socket Programming by Rajkumar Buyya
Socket Programming by Rajkumar BuyyaSocket Programming by Rajkumar Buyya
Socket Programming by Rajkumar Buyya
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
#1 (TCPvs. UDP)
#1 (TCPvs. UDP)#1 (TCPvs. UDP)
#1 (TCPvs. UDP)
 
Python networking
Python networkingPython networking
Python networking
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
 
Multiuser chat application using java
Multiuser chat application using javaMultiuser chat application using java
Multiuser chat application using java
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
 
Socket
SocketSocket
Socket
 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
 
Advanced Java Topics
Advanced Java TopicsAdvanced Java Topics
Advanced Java Topics
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in Java
 

More from Riccardo Cardin

More from Riccardo Cardin (9)

Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Design Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionDesign Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency Injection
 
Design Pattern Comportamentali
Design Pattern ComportamentaliDesign Pattern Comportamentali
Design Pattern Comportamentali
 
Design Pattern Creazionali
Design Pattern CreazionaliDesign Pattern Creazionali
Design Pattern Creazionali
 
Diagrammi di Attività
Diagrammi di AttivitàDiagrammi di Attività
Diagrammi di Attività
 
Diagrammi Use Case
Diagrammi Use CaseDiagrammi Use Case
Diagrammi Use Case
 
Introduzione a UML
Introduzione a UMLIntroduzione a UML
Introduzione a UML
 
Mvc e di spring e angular js
Mvc e di   spring e angular jsMvc e di   spring e angular js
Mvc e di spring e angular js
 
Reactive programming principles
Reactive programming principlesReactive programming principles
Reactive programming principles
 

Recently uploaded

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 

Java - Sockets

  • 1. SOCKETS PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 – 2016 rcardin@math.unipd.it
  • 2. Programmazione concorrente e distribuita SUMMARY  Introduction  Sockets  Client program  Server program  Protocol 2Riccardo Cardin
  • 3. Programmazione concorrente e distribuita INTRODUCTION  Client-server applications  The server provides some service  The client uses the server provided by the server  The communication must be reliable  TCP provides a reliable, point-to-point communication chanel over the Internet  Each program binds a socket to its end of connection  The communication is realized reading and writing from and to the socket bound to the connection 3Riccardo Cardin
  • 4. Programmazione concorrente e distribuita INTRODUCTION  A server runs on a specific host and has a socket bound to a specific port  The server waits, listening to the socket  The client knows the hostname and port number on which the server is listening  Tries to randezvous with the server and binds a local port number to use during connection 4Riccardo Cardindistribuita
  • 5. Programmazione concorrente e distribuita INTRODUCTION 5Riccardo Cardin
  • 6. Programmazione concorrente e distribuita SOCKETS  An endpoint is a combination of an IP address and a port number  Every TCP connection is uniquely identified by its two endpoints  The class java.net.Socket implements the client side of a two-way connection  Sits on top of a platform-dependent implementation  The class java.net.ServerSocket implements the server side, that listen for connections to clients 6Riccardo Cardin A socket is one endpoint of a two-way communication link between two programs running on the network. 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.
  • 7. Programmazione concorrente e distribuita EXAMPLE: ECHO PROGRAM  Let’s implement an example program  The EchoClient writes to and reads from the socket  Open a socket.  Open an input stream and output stream to the socket.  Read from and write to the stream according to the server's protocol.  Close the streams.  Close the socket. 7Riccardo Cardin The example program implements a client, EchoClient, that connects to an echo server. The echo server receives data from its client and echoes it back. The example EchoServer implements an echo server. (Alternatively, the client can connect to any host that supports the Echo Protocol.)
  • 8. Programmazione concorrente e distribuita CLIENT PROGRAM  First of all, let’s open the socket 8Riccardo Cardin // The client has the hostname and port of the server as inputs String hostName = args[0]; int portNumber = Integer.parseInt(args[1]); try ( // Open a socket connection to a host and a port number Socket echoSocket = new Socket(hostName, portNumber); // Build structures that write to the socket PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true); // Build structures that read from the socket BufferedReader in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream())); // Read user input from console BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)) )
  • 9. Programmazione concorrente e distribuita CLIENT PROGRAM  The java.net.Socket class implements a client socket  A socket is binded to an hostname and a port during building process  Sockets implements AutoCloseable  For reading from and writing to a socket we need input and output streams  The try-with-resources statement closes the streams and the socket in the right order  The server socket must be ready to accept incoming connection  Otherwise, the client socket will thrown an exception 9Riccardo Cardin
  • 10. Programmazione concorrente e distribuita CLIENT PROGRAM  The protocol have to be implemented manually  How the socket information are interpreted is dependent from which stream is used to read from it  A Ctrl+C is interpreted as an end-of-input  The communication protocol is totally custom  For example, talking to an HTTP server will be more complicated 10Riccardo Cardin String userInput; // Reading user input until Ctrl+C is read while ((userInput = stdIn.readLine()) != null) { // Writing information to socket out.println(userInput); // Reading information to socket System.out.println("echo: " + in.readLine()); }
  • 11. Programmazione concorrente e distribuita CLIENT PROGRAM 11Riccardo Cardin
  • 12. Programmazione concorrente e distribuita SERVER PROGRAM  To the other end of endpoint a server is listening to some incoming messages 12Riccardo Cardin // The port number on which the server will listening int portNumber = Integer.parseInt(args[0]); try ( // A ServerSocket waits a client’s message on a specific port ServerSocket serverSocket = new ServerSocket(portNumber); // Once a message has arrived, a socket is created to manage // the connection with the client Socket clientSocket = serverSocket.accept(); // Structure to write to the socket PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); // Structure to read from the socket BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); )
  • 13. Programmazione concorrente e distribuita SERVER PROGRAM 13Riccardo Cardin
  • 14. Programmazione concorrente e distribuita SERVER PROGRAM  Using java.net.ServerSocket a server can accept a connection from a client  The accept method waits until a client request a connection to the host and port of the server  A Socket is created on the same port, to managed the connection with the new client  It is possible to have a «multiple client» server  For each new connection, create a dedicated Thread  The communication is manage using streams 14Riccardo Cardin while (true) { // accept a connection // create a thread to deal with the client }
  • 15. Programmazione concorrente e distribuita SERVER PROGRAM 15Riccardo Cardin
  • 16. Programmazione concorrente e distribuita PROTOCOL  Who speaks first?  The problem with socket communication is that it is a low level type of communication  The protocol is custom for each type of implementation  Usually a dedicated class is used to implement the protocol  Given a received message, it returns the next action to do  Server port is part of the protocol  The server MUST be already listening for incoming connection when clients try to communicate with it  Only the accept method of ServerSocket is blocking 16Riccardo Cardin
  • 17. Programmazione concorrente e distribuita EXAMPLES 17Riccardo Cardin https://github.com/rcardin/pcd-snippets
  • 18. Programmazione concorrente e distribuita REFERENCES  Lesson: All About Socket https://docs.oracle.com/javase/tutorial/networking/sockets/  Echo Protocol http://tools.ietf.org/html/rfc862  Does the port change when a TCP connection is accepted by a server? http://stackoverflow.com/questions/2997754/does-the- port-change-when-a-tcp-connection-is-accepted-by-a-server 18Riccardo Cardin