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)

cli1 cli2 cli3

server

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!

Java Network Programming

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()) ...

5MB Sizes 0 Downloads 192 Views

Recommend Documents

Java Network Programming and Distributed Computing
Internet, Web applications, and Web services, the majority of today's programs and applications require ... basic concepts involved with networking and the practical application of the skills necessary to be an ...... We use the term devices in this

Introduction to Java Programming
LiveLab is a programming course assessment and management system. Students can .... B MySQL Tutorial. C Oracle Tutorial. D Microsoft Access Tutorial. E Introduction to Database Systems. F Relational Database Concept. G Database Design ...... In 1954,

FRC Java Programming - GitHub
FRC Java Programming Last Updated: 1/11/2016 ..... NI Update Service .... network. When you have entered the team number and the roboRIO is connected, ...

Introduction to Java Programming
problem-driven complete revision new problems early console input hand trace box multidimensional arrays. Sudoku problem simplified basic GUI earlier .... T Networking Using Datagram Protocol. U Creating Internal ..... the outset, it is helpful to re

JXTA_ Java P2P Programming
After you have selected OK, configuration files and directories will be written to disk and the platform will boot. Before the platform fully boots, you will be presented with a security login dialog that requests the name and password you chose in t

COMP201 Java Programming
COMP201 Topic 2 / Slide 2. Objective and Outline. ○ Objective. ▫ Show basic programming concepts. ○ Outline. ▫ What do java programs look like? ▫ Basic ingredients. – Java primitive types. – Variables and constants. – Operators and co

pdf-1879\programming-android-java-programming-for-the-new ...
Try one of the apps below to open or edit this item. pdf-1879\programming-android-java-programming-for-the-new-generation-of-mobile-devices.pdf.

pdf on java programming language
There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. pdf on java ...

introduction-to-java-programming-comprehensive-9th-edition.pdf ...
introduction-to-java-programming-comprehensive-9th-edition.pdf. introduction-to-java-programming-comprehensive-9th-edition.pdf. Open. Extract. Open with.

Effective Java: Programming Language Guide
Jun 1, 2001 - the examples, you may have to add one or both of these import ..... A unifying theme underlies this Item and Item 21, which describes the ...

Introduction to Programming Using Java
languages such as Java, Pascal, or C++. A program written in a ...... If I say “the President went fishing,” I mean that George W. Bush went fishing. But if I say.

Advance Java Programming Techniques.pdf
products remains at the sole discretion of Oracle. Page 3 of 49. Advance Java Programming Techniques.pdf. Advance Java Programming Techniques.pdf. Open.