Top Banner
Larissa Barreda Michael Bertka Rocio Cortes Jaime Flores Java Sockets
27

Java Sockets

Jan 28, 2016

Download

Documents

Inga

Java Sockets. Larissa Barreda Michael Bertka Rocio Cortes Jaime Flores. What are Sockets?. Programming abstraction (API) Originated as BSD UNIX Now part of modern OS & languages. File vs. Socket API. File f = new File("test"); FileInputStream fis = new FileInputStream( f); - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java Sockets

Larissa Barreda

Michael Bertka

Rocio Cortes

Jaime Flores

Java Sockets

Page 2: Java Sockets
Page 3: Java Sockets

What are Sockets?

• Programming abstraction (API)

• Originated as BSD UNIX

– Now part of modern OS & languages

Page 4: Java Sockets

File vs. Socket API

File f = new File("test");FileInputStream fis = new FileInputStream( f);char c = fis.read();fis.close();

Socket s = new Socket ("www.cs.utep.edu", 80);InputStream is = s.getInputStream();char c = is.read();s.close();

Page 5: Java Sockets

Socket Types

• Streaming– Connection based

• Bi-directional• Reliable, in-order (FIFO)

• Datagram– Connectionless– Non-reliable– Out of order delivery

Page 6: Java Sockets

Sockets Advantages

• Better Net efficiency

• Socket supports both synchronous

and asynchronous

• Client application scan run multiple socket connections to a server

Page 7: Java Sockets

Data Stream

123 “abc” 66.6

… 7 4 5 6 1 3 0 …

… 7 4 5 6 1 3 0 …

Applets, Shapes, etc…

Object Stream

Buffered Stream

InputStream / OutputStream

Java I/O Streams

Page 8: Java Sockets

Network Communication

Byte BasedByte-stream or byte-array

Protocol TypesText-based: HTTP, SMTP, SOAP, …

Bit-based: DNS, LDAP, SNMP

IssuesText: encoding (Unicode 16bit > 8bit )

Bit: byte ordering

Page 9: Java Sockets

Network Ports• Internet host address

– Example: 128.59.16.1

• How to offer multiple services?– Mailbox approach

– Port number addressing [0-65,535](216)– Example: 128.59.16.1 : TCP: 80

128.59.16.20

HTTPD

TELNETD

named

TCP: 80

TCP: 23

UDP: 53Internet

IP Host

Page 10: Java Sockets

Example: HTTP client

• Trivial HTTP 1.0 Client– Application-layer protocol over TCP– Text-based Protocol

:Browser :www Server

TCP Connect

“GET /” CR CF

“CONTENT-TYPE=text/html CONTENT-LENGTH=122…”

Page 11: Java Sockets

HTTP Client (No Error Handling)

Socket socket = new Socket ("www.cs.utep.edu", 80);

BufferdOutputStream ostream =new BufferedOutputStream (socket.getOutputStream() );

byte[] request = "GET/\r\n".getBytes("ISO-8859-1");ostream.write(request);ostream.flush();

BuffereInputStream istream =new BufferedInputStream(socket.getInputStream() );

byte[] buffer = new byte[4096];int count = istream.read(buffer);while (count != -1){ System.out.print(new String(buffer, 0, count) ); count = istream.read(buffer);}socket.close();

Page 12: Java Sockets

Stream Socket Error Handling• Network fail !

– Applications must be aware of failures• Sockets are scarce OS resources

– Don’t relay on garbage collection; close() when done!

Socket socket = null;try { socket = new Socket ("www.cs.utep.edu", 80); // Perform i/0} catch (Throwable e){ // Application-specific error recovery} finally { socket.close() // no matter what close()!}

Page 13: Java Sockets

Server Stream Sockets

• Brief Introduction to servers…

- Apache one of the most popular web server on the internet

- Developed by: “The Apache HTTP Server Project”

- Goal of this project: secure, public domain, efficient and extensible server

Page 14: Java Sockets

Server Stream Sockets

• Stream sockets provide for a data flow without record boundaries

• Streams are reliable, they return unduplicated data

• Receipt of stream messages is guaranteed

• When to use?- When data must be guaranteed to arrive

- When data size is large

Page 15: Java Sockets

Server Stream Sockets

Example:

• A telephone call provides a good analogy for a stream. Under normal circumstances, the receiving party hears what you say in the order that you say it, without duplication or loss. Stream sockets are appropriate, for example, for implementations such as the File Transfer Protocol (FTP), which facilitates transferring ASCII or binary files of arbitrary size.

Page 16: Java Sockets

Java Threads

• Why parallelize ?- Prevent blocking from malformed requests

- Deal with writing to slow clients

- Interleave processing/file reading

• How ?- Multiple threads

- Shared memory

- Interleaved execution

Page 17: Java Sockets

Threaded Server Pattern

ServerSocket server = new ServerSocket (80);

While (isActive) {

Socket socket = server.accept ( );

Handler handler = new Handler (socket);

handler.start ( );

}

Page 18: Java Sockets

Threaded Server Pattern

Public class Handler extends Thread {

protected final Socket socket;

Public Handler (Socket socket) {this.socket = socket;

}

Public void run ( ) {Try {

// Protocol Impl.}Finally {

socket.close ( );}}}

Page 19: Java Sockets

Datagram Sockets

• Connectionless

• Unreliable

• Limited payload

• When to use– Simple request-response protocol

– Small request/replies (fit datagram)

– Stateless/re-entrant servers

– Real-time streaming

Page 20: Java Sockets

UDP Client Example

DatagramSocket socket = new DatagramSOcket ( );byte[ ] data = “hello world”.getBytes ( );

DatagramPacket packet =new Datagram packet (data, data.length, InetAddress.getByName (“localhost”), 1234);

socket.send(packet);

data = “followup call”.getBytes ( );packet.setData (data);

socket.send (packet);

Page 21: Java Sockets

UDP Server Example

DatagramSocket socket = new DatagramSocket (1234);

byte [ ] buffer = new byte [512];

DatagramPacket packet = new DatagramPacket (buffer,buffer.length);

While (true) {socket.receive (packet);

String msg = new String (packet.getData ( ), 0, packet.getLength( )));

System.out.println ( new java.util.Date ( ) + “: “ + msg);packet.setLength (buffer.length);

Page 22: Java Sockets

MultiCast

• One-to-Many transmission – Efficient way of distributing information to many hosts

without having to create a client/server connection for

each host – Special Range of IP Addresses

• Assigned by Internet Assigned Numbers Authority (IANA)

• 224.0.0.0 – 239.255.255.255

• Same Socket API as UDP– A MulticastSocket is a (UDP) DatagramSocket– Capable of joining “groups” of multicast hosts

• Not Universally Available

Page 23: Java Sockets

SSL Sockets

• Secure Communications– Layered Over TCP– Integrity Protection (protects against message

modification)– Authentication– Confidentiality (encryption)

• Drop-in replacement (subclasses)– Socket SSLSocket– Server Socket SSLServerSocket

• Key Management (trust relationship)– Keytool command-line utility– Creates public/private keys

• Stored in “keystores”– Java VM invocation with keystore info

Page 24: Java Sockets

Non-Blocking Java I/O

• Thread scaling issues– E.g. HTTP server with 1000’s of

connections

• JDK 1.4 introduced non-blocking I/O– Processing done in one thread instead

of multiple– Improves performance– Java.nio.* package

Page 25: Java Sockets

Advanced Issues

• Thread pools– Resource management

• Binding to specific interfaces– Binding to a specific interface (security)

• Swing– Single threaded– Network operations in non-swing thread– Use Swing.Utilities.invokeLater()

Page 26: Java Sockets

Socket FAQ’s

• Wrong host/port/protocol– “localhost”, 127.0.0.1, “www” vs

www.foo.com• Ignoring I/O exceptions• Streams:

– Flush() when done– Use buffered reader/stream– Close connections when done

• Datagrams– Packet.setLength() before reuse– Test in a lossy environment

Page 27: Java Sockets

Socket FAQ’s

• Wait-forever– Use Socket.setSoTimeout()– Catch InterruptedIOException

• Byte-Alignment issues– Network byte order

• Security restrictions (applets)

• Unix restricts non-root servers to ports > 1024