SlideShare a Scribd company logo
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!

More Related Content

PPT
Multi threading
PDF
Introduction+To+Java+Concurrency
PPT
Java Multithreading and Concurrency
PPTX
Threading in C#
PDF
Multithreading in Java
PPTX
.NET: Thread Synchronization Constructs
Multi threading
Introduction+To+Java+Concurrency
Java Multithreading and Concurrency
Threading in C#
Multithreading in Java
.NET: Thread Synchronization Constructs

What's hot (20)

PPTX
.NET Multithreading/Multitasking
PPT
Threads c sharp
PPTX
PPTX
Chap3 multi threaded programming
ODP
Multithreading 101
PPTX
Threading
PPTX
PDF
Java 8 - Stamped Lock
PPT
Threads in java
PDF
Java Thread Synchronization
ODP
Multithreading Concepts
PPT
Threads
PPT
Intro To .Net Threads
PPT
Learning Java 3 – Threads and Synchronization
PPT
04 threads
PPT
Threads c sharp
PPTX
Tutorial 3 getting started with omnet
PDF
Java Multithreading Using Executors Framework
PPTX
Java Thread & Multithreading
.NET Multithreading/Multitasking
Threads c sharp
Chap3 multi threaded programming
Multithreading 101
Threading
Java 8 - Stamped Lock
Threads in java
Java Thread Synchronization
Multithreading Concepts
Threads
Intro To .Net Threads
Learning Java 3 – Threads and Synchronization
04 threads
Threads c sharp
Tutorial 3 getting started with omnet
Java Multithreading Using Executors Framework
Java Thread & Multithreading
Ad

Viewers also liked (20)

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

Similar to Jnp (20)

PDF
Lecture10
PPT
Socket Programming
PDF
28 networking
PPTX
PPT
Unit 8 Java
PPTX
分散式系統
PPTX
Advance Java-Network Programming
ODP
Sockets in nach0s
PDF
PDF
Java Programming - 08 java threading
PPT
Java Socket Programming
PPTX
PPT
Sockets.ppt socket sofcv ohghjagshsdjjhjfb
PPTX
Tcp/ip server sockets
PPT
Basic Networking in Java
PPTX
Java networking
PPT
Network programming in Java
PPT
Networking.ppt(client/server, socket) uses in program
PPT
Network Programming in Java
DOCX
Lab manual cn-2012-13
Lecture10
Socket Programming
28 networking
Unit 8 Java
分散式系統
Advance Java-Network Programming
Sockets in nach0s
Java Programming - 08 java threading
Java Socket Programming
Sockets.ppt socket sofcv ohghjagshsdjjhjfb
Tcp/ip server sockets
Basic Networking in Java
Java networking
Network programming in Java
Networking.ppt(client/server, socket) uses in program
Network Programming in Java
Lab manual cn-2012-13

Recently uploaded (20)

PPTX
Programs and apps: productivity, graphics, security and other tools
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
cuic standard and advanced reporting.pdf
PDF
KodekX | Application Modernization Development
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Encapsulation theory and applications.pdf
Programs and apps: productivity, graphics, security and other tools
The AUB Centre for AI in Media Proposal.docx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Per capita expenditure prediction using model stacking based on satellite ima...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
“AI and Expert System Decision Support & Business Intelligence Systems”
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Machine learning based COVID-19 study performance prediction
cuic standard and advanced reporting.pdf
KodekX | Application Modernization Development
Advanced methodologies resolving dimensionality complications for autism neur...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Network Security Unit 5.pdf for BCA BBA.
Reach Out and Touch Someone: Haptics and Empathic Computing
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
NewMind AI Weekly Chronicles - August'25 Week I
The Rise and Fall of 3GPP – Time for a Sabbatical?
Understanding_Digital_Forensics_Presentation.pptx
Encapsulation theory and applications.pdf

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!