Networking - Client/Server

Getting started (testing on your PC)

Don't forget: Port numbers must be greater than 1024 and less than 65000, other than that restriction, anything goes

To run on PCs, you must have TCP/IP running. I.e., If you are using a dial-up connection (telnet), you need to have it running for the client-server experiments. Even though you are only talking to your local machine for both client and server the network software must be loaded.

Core Java suggests IP address 127.0.0.1 and port 8187 (or whatever you have specified). This is a special address called the local loopback address which denotes the local machine (CoreV2, Chapter 3)
java.net

Client/Server Programming in Java

In Java, creating TCP/IP socket connections is made straightforward.

The simplest socket model:

Minimal Server

TCP/IP server applications rely on a networking class provided by Java: ServerSocket. This class takes most of the work out of establishing a server. Note the ServerSocket and Socket variables.

Minimal Client

The client side of a TCP/IP application relies on the Socket class. Again, much of the work involved in establishing connections has been done by the Socket class. This client will attach to the server presented above and echo everything sent by the server to stdout.

To Run

See these additional simple examples (I will cover them in class too).
Also EchoServer.java

Multiple Clients

We want to allow multiple clients at the server at a time so one client is not a hog. How? Threads.

This server reads the client(s) input a line at a time and echos it. Note the use of nested top-level classes here also. See Java in a Nutshell, page 102.

note also that Socket accept() waits for a connection. This method will block (idle) the current thread until a connection is made.

Core JavaV2, page 151, ThreadedEchoServer.java has a 5.0 version with java.util.Scanner for working with text.

running

java tutorial again

Core Java, Volume II, Chapter 3 (pages 146-185) has some very nice examples of using the web and client servers and CGI scripts... Use the CD they provided with the book and run some of these.

CGI Programming in Java