Java Sockets and Server Sockets

5/16/99


Click here to start


Table of Contents

Java Sockets and Server Sockets

In this talk:

I assume you

Applet Network Security Restrictions

Datagrams

Packets Allow Error Correction

Abstraction

Sockets

Socket Operations

The java.net.Socket class

Constructing a Socket

Opening Sockets

You must at least specify the remote host and port to connect to.

You cannot just connect to any port on any host. The remote host must actually be listening for connections on that port.

PPT Slide

Picking an IP address

Choosing a Local Port

Sending and Receiving Data

Reading Input from a Socket

For example

Writing Output to a Socket

Discard

Reading and Writing to a Socket

Some protocols require the reads and the writes to be interlaced. That is:

Other protocols, such as HTTP 1.0, have multiple writes, followed by multiple reads, like this:

Other protocols don't care and allow client requests and server responses to be freely intermixed.

PPT Slide

Socket Options

These methods to return information about the socket:

Servers

Server Sockets

Multiple Clients

Threading

Queueing

The java.net.ServerSocket Class

Constructors

Constructing Server Sockets

When a ServerSocket object is created, it attempts to bind to the port on the local host given by the port argument.

On Unix systems (but not Windows or the Mac) your program must be running as root to bind to a port between 1 and 1023.

Expanding the Queue

Choosing an IP address

Example

On a server with multiple IP addresses, the getInetAddress() method tells you which one this server socket is listening to.

The accept() and close() methods provide the basic functionality of a server socket.

Reading Data with a ServerSocket

Example

Better Example

Writing Data to a Client

Interacting with a Client

Adding Threading to a Server

Adding a Thread Pool to a Server

Every time you pass through this loop, a new thread gets created. Every time a connection is finished the thread is disposed of.

Thread Pools

Setting Server Socket Options

Utility Methods

UDP

The UDP Classes

java.net. DatagramPacket

java.net.DatagramSocket

UDP ports

Two DatagramPacket Constructors

For example,

With a destination:

DatagramPackets are not immutable.

java.net.DatagramSocket

Sending UDP Datagrams

For example,

Receiving UDP Datagrams

PPT Slide

For example,

To Learn More

Author: Elliotte Rusty Harold

Email: elharo@metalab.unc.edu

Home Page: http://metalab.unc.edu/javafaq/

Download presentation source