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!

Jnp

  • 1.
  • 2.
    Outline Sockets in Java TCPSockets UDP Sockets Multithreading
  • 3.
    The Sockets Interface To communicateyou have to connect the two ends
  • 4.
    Sockets in Java Thesockets 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 isan end-point
  • 6.
    Socket Address Two kindsof sockets: tcp & udp Each socket: IP address port number
  • 7.
    Java Sockets Socket classesbelong to java.net package Socket, ServerSocket & DatagramSocket Each type works quite differently Java help is your friend: read it
  • 8.
    Sockets on thecommand line? Many tools available: sock (lab#2) nc (or netcat) telnet (tcp only)
  • 9.
    TCP client Client startsthe 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 providesa data stream Byte-oriented vs. line-oriented I/O Scanner & PrintWriter InputStream & OutputStream UDP exchanges byte arrays only
  • 11.
    Exception handling Some methodscan 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 Itconnects 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 Serverwaits 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 clientscan be server AT ONCE Use of fork Use of Threads (Java) server cli1 cli2 cli3
  • 15.
    Threads in Java Yourclass 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 Whatis 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 DatagramPacketobjects 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 Addressesare 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 Returnsdatagram 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 protocolsare handled by the same server program It can be like an extended concurrent server with serveral types of threads
  • 21.
    Now it isyour time to start coding!