Java Network Programming
Java Network Programming
Java Network Programming
Sockets in Java
TCP Sockets
UDP Sockets
Multithreading
The Sockets
Interface
To communicate you have to
connect the two ends
Sockets in Java
Each socket:
IP address
port number
Java Sockets
sock (lab#2)
nc (or netcat)
It sends a request
! out.println("GET / HTTP/1.0");
! out.println();
! while(in.hasNext()) System.out.println(in.nextLine());
! }
}
Basic TCP server
cli1
Several clients can be
server AT ONCE
cli2 server
Use of fork
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
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
It can be like an
extended concurrent
server with serveral
types of threads
Now it is your time to start coding!