SlideShare una empresa de Scribd logo
1 de 21
Descargar para leer sin conexión
Java Network Programming
©Miguel Sánchez 2010
Outline
Sockets in Java
TCP Sockets
UDP Sockets
Multithreading
The Sockets
Interface
To communicate you have to
connect the two ends
Sockets in Java
The sockets API is
available in many
languages
Protocol stack is part
of most Operating
Systems
Java provides a clean
and easy access to the
sockets
A socket is an end-point
Socket Address
Two kinds of sockets:
tcp & udp
Each socket:
IP address
port number
Java Sockets
Socket classes belong to java.net
package
Socket, ServerSocket &
DatagramSocket
Each type works quite differently
Java help is your friend: read it
Sockets on the command line?
Many tools available:
sock (lab#2)
nc (or netcat)
telnet (tcp only)
TCP client
Client starts the connection the server
Socket s=new Socket(“hostname”,25);
Connection is closed by:
s.close();
Something else in between is desired!
Socket Input/Output
TCP provides a data stream
Byte-oriented vs. line-oriented I/O
Scanner & PrintWriter
InputStream & OutputStream
UDP exchanges byte arrays only
Exception handling
Some methods can cause Exceptions
Exceptions may be caught to be handled
by your code
Exceptions can be thrown not to be
handled by your code
try/catch vs throws clauses
Basic TCP client
It connects to a web server
It sends a request
It receives and prints the response
import java.net.*;
import java.io.*;
import java.util.*;
class ClientTCP {
public static void main(String args[]) throws UnknownHostException, IOException {
! Socket s=new Socket("www.upv.es",80);
! Scanner in=new Scanner(s.getInputStream());
! PrintWriter out=new PrintWriter(s.getOutputStream(),true);
! out.println("GET / HTTP/1.0");
! out.println();
! while(in.hasNext()) System.out.println(in.nextLine());
! }
}
Basic TCP server
Server waits for a new connection from a client
Server transmits a message to the client and
closes the connection
Repeat
import java.net.*;
import java.io.*;
import java.util.*;
class ServerTCP {
public static void main(String args[]) throws UnknownHostException,
IOException {
! ServerSocket ss = new ServerSocket(8888);
! while(true) {
! ! Socket s = ss.accept();
! ! Scanner in=new Scanner(s.getInputStream());
! ! PrintWriter out=new PrintWriter(s.getOutputStream(),true);
! ! out.println("Hello Client!");
! ! s.close();
! ! }
! }
}
Multithread servers
Several clients can be
server AT ONCE
Use of fork
Use of Threads (Java)
server
cli1
cli2
cli3
Threads in Java
Your class extends Thread class
Code of thread is defined on run() method
start() method call will start running a new thread of
excution
class MyThread extends Thread {
public void run() { // thread code here
while(true) System.out.print("T");
}
public static void main(String args[]) {
Thread t = new MyThread();
t.start();
while(true) System.out.print("M");
}
}
Basic Concurrent Server
What is the difference from basic server?
import java.net.*;
import java.io.*;
import java.util.*;
class CServerTCP extends Thread {
PrintWriter myOut=null;
public CServerTCP(PrintWriter out) { myOut=out; }
public void run() {myOut.println("Hello Client!"); }
public static void main(String args[]) throws UnknownHostException, IOException {
! ServerSocket ss = new ServerSocket(8888);
! while(true) {
! ! Socket s = ss.accept();
! ! Scanner in=new Scanner(s.getInputStream());
! ! PrintWriter out=new PrintWriter(s.getOutputStream(),true);
! ! new CServerTCP(out).start();
! ! }
! }
}
UDP Sockets
DatagramSocket sends/receives
DatagramPacket objects
A DatagramPacket has a data buffer in
the form of a byte array
Destination address is defined for each
DatagramPacket (remember: no
connection here!)
Sample UDP sender
Addresses are expressed as InetAddress
Buffer length changes with content
nc -u -l 7777
import java.net.*;
import java.io.*;
import java.util.*;
class UDPsender {
public static void main(String args[]) throws UnknownHostException, IOException {
! DatagramSocket ds = new DatagramSocket(12345);
! byte buffer[] = new String("Hello World!n").getBytes();
! InetAddress dst = InetAddress.getByName("127.0.0.1");
! DatagramPacket dp = new DatagramPacket(buffer,buffer.length,dst,7777);
! ds.send(dp);!
! }
}
UDP echo server
Returns datagram back to the sender
import java.net.*;
import java.io.*;
import java.util.*;
class UDPecho {
public static void main(String args[]) throws UnknownHostException, IOException {
! DatagramSocket ds = new DatagramSocket(12345);
! byte buffer[] = new byte[1024];
! DatagramPacket dp = new DatagramPacket(buffer,buffer.length);
! for(;;) {
! ! ds.receive(dp);!
! ! dp.setAddress(dp.getAddress()); // back to the sender
! ! dp.setPort(dp.getPort());
! ! ds.send(dp);
! ! }
! }
}
Multiprotocol server
Several protocols are
handled by the same
server program
It can be like an
extended concurrent
server with serveral
types of threads
Now it is your time to start coding!

Más contenido relacionado

La actualidad más candente

.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programmingraksharao
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101Tim Penhey
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped LockHaim Yadid
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threadsrchakra
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharpDeivaa
 
Tutorial 3 getting started with omnet
Tutorial 3   getting started with omnetTutorial 3   getting started with omnet
Tutorial 3 getting started with omnetMohd Batati
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkArun Mehra
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreadingjehan1987
 

La actualidad más candente (20)

.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharp
 
Threads
ThreadsThreads
Threads
 
Java adv
Java advJava adv
Java adv
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
 
Threading
ThreadingThreading
Threading
 
multi threading
multi threadingmulti threading
multi threading
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped Lock
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Threads
ThreadsThreads
Threads
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
04 threads
04 threads04 threads
04 threads
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharp
 
Tutorial 3 getting started with omnet
Tutorial 3   getting started with omnetTutorial 3   getting started with omnet
Tutorial 3 getting started with omnet
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
 

Destacado

Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket ProgrammingMousmi Pawar
 
Socket Programming Tutorial
Socket Programming TutorialSocket Programming Tutorial
Socket Programming TutorialJignesh Patel
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.comphanleson
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagarNitish Nagar
 
Networking Chapter 4
Networking Chapter 4Networking Chapter 4
Networking Chapter 4mlrbrown
 
Networking Chapter 5
Networking Chapter 5Networking Chapter 5
Networking Chapter 5mlrbrown
 
X$Tables And Sga Scanner, DOAG2009
X$Tables And Sga Scanner, DOAG2009X$Tables And Sga Scanner, DOAG2009
X$Tables And Sga Scanner, DOAG2009Frank
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Harmeet Singh(Taara)
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scannerArif Ullah
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructorShivam Singhal
 
Network Socket Programming with JAVA
Network Socket Programming with JAVANetwork Socket Programming with JAVA
Network Socket Programming with JAVADudy Ali
 
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)VLSI SYSTEM Design
 

Destacado (20)

Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Basics of sockets
Basics of socketsBasics of sockets
Basics of sockets
 
Sockets
SocketsSockets
Sockets
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
Ppt of socket
Ppt of socketPpt of socket
Ppt of socket
 
Socket Programming Tutorial
Socket Programming TutorialSocket Programming Tutorial
Socket Programming Tutorial
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Profinet Design
Profinet DesignProfinet Design
Profinet Design
 
Networking Chapter 4
Networking Chapter 4Networking Chapter 4
Networking Chapter 4
 
Networking Chapter 5
Networking Chapter 5Networking Chapter 5
Networking Chapter 5
 
X$Tables And Sga Scanner, DOAG2009
X$Tables And Sga Scanner, DOAG2009X$Tables And Sga Scanner, DOAG2009
X$Tables And Sga Scanner, DOAG2009
 
Profinet system design - Andy Verwer
Profinet system design - Andy VerwerProfinet system design - Andy Verwer
Profinet system design - Andy Verwer
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
Profibus commissioning and maintenance - Richard Needham
Profibus commissioning and maintenance - Richard NeedhamProfibus commissioning and maintenance - Richard Needham
Profibus commissioning and maintenance - Richard Needham
 
Network Socket Programming with JAVA
Network Socket Programming with JAVANetwork Socket Programming with JAVA
Network Socket Programming with JAVA
 
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
 

Similar a Jnp

Similar a Jnp (20)

Lecture10
Lecture10Lecture10
Lecture10
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
28 networking
28  networking28  networking
28 networking
 
Java 1
Java 1Java 1
Java 1
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
分散式系統
分散式系統分散式系統
分散式系統
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programming
 
Sockets in nach0s
Sockets in nach0sSockets in nach0s
Sockets in nach0s
 
Ipc
IpcIpc
Ipc
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
A.java
A.javaA.java
A.java
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Java
 
Java networking
Java networkingJava networking
Java networking
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Networking.ppt(client/server, socket) uses in program
Networking.ppt(client/server, socket) uses in programNetworking.ppt(client/server, socket) uses in program
Networking.ppt(client/server, socket) uses in program
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in Java
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
 
Socket & Server Socket
Socket & Server SocketSocket & Server Socket
Socket & Server Socket
 

Último

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 

Último (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 

Jnp

  • 2. Outline Sockets in Java TCP Sockets UDP Sockets Multithreading
  • 3. The Sockets Interface To communicate you have to connect the two ends
  • 4. Sockets in Java The sockets API is available in many languages Protocol stack is part of most Operating Systems Java provides a clean and easy access to the sockets
  • 5. A socket is an end-point
  • 6. Socket Address Two kinds of sockets: tcp & udp Each socket: IP address port number
  • 7. Java Sockets Socket classes belong to java.net package Socket, ServerSocket & DatagramSocket Each type works quite differently Java help is your friend: read it
  • 8. Sockets on the command line? Many tools available: sock (lab#2) nc (or netcat) telnet (tcp only)
  • 9. TCP client Client starts the connection the server Socket s=new Socket(“hostname”,25); Connection is closed by: s.close(); Something else in between is desired!
  • 10. Socket Input/Output TCP provides a data stream Byte-oriented vs. line-oriented I/O Scanner & PrintWriter InputStream & OutputStream UDP exchanges byte arrays only
  • 11. Exception handling Some methods can cause Exceptions Exceptions may be caught to be handled by your code Exceptions can be thrown not to be handled by your code try/catch vs throws clauses
  • 12. Basic TCP client It connects to a web server It sends a request It receives and prints the response import java.net.*; import java.io.*; import java.util.*; class ClientTCP { public static void main(String args[]) throws UnknownHostException, IOException { ! Socket s=new Socket("www.upv.es",80); ! Scanner in=new Scanner(s.getInputStream()); ! PrintWriter out=new PrintWriter(s.getOutputStream(),true); ! out.println("GET / HTTP/1.0"); ! out.println(); ! while(in.hasNext()) System.out.println(in.nextLine()); ! } }
  • 13. Basic TCP server Server waits for a new connection from a client Server transmits a message to the client and closes the connection Repeat import java.net.*; import java.io.*; import java.util.*; class ServerTCP { public static void main(String args[]) throws UnknownHostException, IOException { ! ServerSocket ss = new ServerSocket(8888); ! while(true) { ! ! Socket s = ss.accept(); ! ! Scanner in=new Scanner(s.getInputStream()); ! ! PrintWriter out=new PrintWriter(s.getOutputStream(),true); ! ! out.println("Hello Client!"); ! ! s.close(); ! ! } ! } }
  • 14. Multithread servers Several clients can be server AT ONCE Use of fork Use of Threads (Java) server cli1 cli2 cli3
  • 15. Threads in Java Your class extends Thread class Code of thread is defined on run() method start() method call will start running a new thread of excution class MyThread extends Thread { public void run() { // thread code here while(true) System.out.print("T"); } public static void main(String args[]) { Thread t = new MyThread(); t.start(); while(true) System.out.print("M"); } }
  • 16. Basic Concurrent Server What is the difference from basic server? import java.net.*; import java.io.*; import java.util.*; class CServerTCP extends Thread { PrintWriter myOut=null; public CServerTCP(PrintWriter out) { myOut=out; } public void run() {myOut.println("Hello Client!"); } public static void main(String args[]) throws UnknownHostException, IOException { ! ServerSocket ss = new ServerSocket(8888); ! while(true) { ! ! Socket s = ss.accept(); ! ! Scanner in=new Scanner(s.getInputStream()); ! ! PrintWriter out=new PrintWriter(s.getOutputStream(),true); ! ! new CServerTCP(out).start(); ! ! } ! } }
  • 17. UDP Sockets DatagramSocket sends/receives DatagramPacket objects A DatagramPacket has a data buffer in the form of a byte array Destination address is defined for each DatagramPacket (remember: no connection here!)
  • 18. Sample UDP sender Addresses are expressed as InetAddress Buffer length changes with content nc -u -l 7777 import java.net.*; import java.io.*; import java.util.*; class UDPsender { public static void main(String args[]) throws UnknownHostException, IOException { ! DatagramSocket ds = new DatagramSocket(12345); ! byte buffer[] = new String("Hello World!n").getBytes(); ! InetAddress dst = InetAddress.getByName("127.0.0.1"); ! DatagramPacket dp = new DatagramPacket(buffer,buffer.length,dst,7777); ! ds.send(dp);! ! } }
  • 19. UDP echo server Returns datagram back to the sender import java.net.*; import java.io.*; import java.util.*; class UDPecho { public static void main(String args[]) throws UnknownHostException, IOException { ! DatagramSocket ds = new DatagramSocket(12345); ! byte buffer[] = new byte[1024]; ! DatagramPacket dp = new DatagramPacket(buffer,buffer.length); ! for(;;) { ! ! ds.receive(dp);! ! ! dp.setAddress(dp.getAddress()); // back to the sender ! ! dp.setPort(dp.getPort()); ! ! ds.send(dp); ! ! } ! } }
  • 20. Multiprotocol server Several protocols are handled by the same server program It can be like an extended concurrent server with serveral types of threads
  • 21. Now it is your time to start coding!