Essentials of the Java Programming Language - Part 2

Peter Kitson

ISBN : 0201707209

Order a printed copy of this book from Amazon.


Cover Design - Essentials of the Java Programming Language - Part 2
 

For your free electronic copy of this book please verify the numbers below. 

(We need to do this to make sure you're a person and not a malicious script)

Numbers

 




Sample Chapter From Essentials of the Java Programming Language - Part 2
     Copyright © Monica Pawlan



Lesson 1: Socket Communications

[<<BACK] [CONTENTS] [NEXT>>]

Java Programming Language Basics, Part 1, finished with a simple network communications example using the Remote Method Invocation (RMI) application programming interface (API). The RMI example allows multiple client programs to communicate with the same server program without any explicit code to do this because the RMI API is built on sockets and threads.

This lesson presents a simple sockets-based program to introduce the concepts of sockets and multi-threaded programming. A multi-threaded program performs multiple tasks at one time such as fielding simultaneous requests from many client programs.

  • What are Sockets and Threads?
  • About the Examples
  • Example 1: Server-Side Program
  • Example 1: Client-Side Program
  • Example 2: Multithreaded Server Example
  • More Information

Note: See Creating a Threaded Slide Show Applet for another example of how multiple threads can be used in a program.

What are Sockets and Threads?

A socket is a software endpoint that establishes bidirectional communication between a server program and one or more client programs. The socket associates the server program with a specific hardware port on the machine where it runs so any client program anywhere in the network with a socket associated with that same port can communicate with the server program.

A server program typically provides resources to a network of client programs. Client programs send requests to the server program, and the server program responds to the request.

One way to handle requests from more than one client is to make the server program multi-threaded. A multi-threaded server creates a thread for each communication it accepts from a client. A thread is a sequence of instructions that run independently of the program and of any other threads.

Using threads, a multi-threaded server program can accept a connection from a client, start a thread for that communication, and continue listening for requests from other clients.