Java Sockets

Post on 28-Jan-2016

24 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

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

Transcript

Larissa Barreda

Michael Bertka

Rocio Cortes

Jaime Flores

Java Sockets

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

Socket Types

• Streaming– Connection based

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

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

Sockets Advantages

• Better Net efficiency

• Socket supports both synchronous

and asynchronous

• Client application scan run multiple socket connections to a server

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

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

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

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…”

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

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()!}

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

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

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.

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

Threaded Server Pattern

ServerSocket server = new ServerSocket (80);

While (isActive) {

Socket socket = server.accept ( );

Handler handler = new Handler (socket);

handler.start ( );

}

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 ( );}}}

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

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);

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);

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

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

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

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

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

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

top related