SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
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!

Weitere ähnliche Inhalte

Was ist angesagt?

.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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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)
 

Ähnlich wie Jnp

Ähnlich wie 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
 

Kürzlich hochgeladen

Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
[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
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
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
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
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
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

Kürzlich hochgeladen (20)

Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
[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
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
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
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
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
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

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!