Java Sockets and Server Sockets


Click here to start

Table of Contents

Java Sockets and Server Sockets

In this talk:

I assume you

Applet Network Security Restrictions


Packets Allow Error Correction



Socket Operations

The 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


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:


Server Sockets

Multiple Clients



The Class


Constructing Server Sockets

When you create a ServerSocket object, 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


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



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


The UDP Classes DatagramPacket

UDP ports

Two DatagramPacket Constructors

For example,

With a destination:

DatagramPackets are not immutable.

Sending UDP Datagrams

For example,

Receiving UDP Datagrams

PPT Slide

For example,

To Learn More

Author: Elliotte Rusty Harold


Home Page:

Download presentation source