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:
- the server establishes a port number and waits for timeout seconds
for the client to establish a connection. When the client requests a
connection, the server opens the socket connection with the accept method.
- the client establishes connection with host on port port #
- both client and server communicate using handles for InputStream and
OutputStream.
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.
/*
* TCP/IP Graphical Server
*/
import java.awt.*;
import java.net.*;
import java.io.*;
class SimpleServer {
public static void main(String args[]) {
SimpleServer myServer= new SimpleServer();
myServer.start();
}
public void start(){
ServerSocket s=(ServerSocket) null;
Socket s1;
String sendString = "Hello Net World!\n";
int slength;
OutputStream s1out;
// Setup our server on socket 4321
// (wait for 300 seconds before timing out connections)
try {
s = new ServerSocket(4321,300);
} catch (IOException e) { }
// Run the listen/accept loop forever
// Blocks the process not on connection
while (true) {
try {
// Wait here and listen for a connection
s1=s.accept();
// Socket s1=s.accept() tells Java to wait indefinately until
// a client connects to the port of the ServerSocket
// on? go ahead and use the port
// Get an output file handle associated with the socket
// s.accept() returns a Socket object that represents
// the connection that was made
s1out = s1.getOutputStream();
// Send our string!
slength = sendString.length();
for (int i=0; i < slength; i++) {
s1out.write((int)sendString.charAt(i));
}
// Close the connection, but not the server socket
s1.close();
} catch (IOException e) { }
}
}
}
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.
/*
* TCP/IP simple client--Echo back the servers output
*/
import java.awt.*;
import java.net.*;
import java.io.*;
class SimpleClient {
public static void main(String args[]) throws IOException {
SimpleClient myClient= new SimpleClient();
myClient.start();
}
public void start(){
int c;
Socket s;
InputStream sIn;
try {
// Note: this used to need the IPaddress
// (not the machinename) - apparently not true anymore
// obviously you put the name of the machine where your server is running
// better still - get from a prompt or argument passed as shown in future examples
s = new Socket("tiglon.ecst.csuchico.edu",4321);
// Get an input file handle from the socket and read the input
sIn = s.getInputStream();
while ((c = sIn.read()) != -1) {
System.out.print((char)c);
}
// When the EOF is reached, just close the connection and exit
s.close();
} catch (IOException e) { }
}
}
To Run
-
java simpleServer on expert.ecst.csuchico.edu (or edit and run from server specified)
- go to another machine and run
java simpleClient
- much to our surprise we will see this
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
/*
* Cay S. Horstmann & Gary Cornell, Core Java
* Published By Sun Microsystems Press/Prentice-Hall
* Copyright (C) 1997 Sun Microsystems Inc.
* All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for NON-COMMERCIAL purposes
* and without fee is hereby granted provided that this
* copyright notice appears in all copies.
*
* THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR
* WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS
* AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED
* BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*/
/**
* @version 1.10 27 Jun 1997
* @author Cay Horstmann
*/
import java.io.*;
import java.net.*;
public class ThreadedEchoServer {
public static void main(String[] args ) {
ThreadedEchoServer myThreadedServer = new ThreadedEchoServer();
myThreadedServer.start();
}
public void start(){
int i = 1;
try
{ ServerSocket s = new ServerSocket(8189);
for (;;)
{ Socket incoming = s.accept( );
System.out.println("Spawning " + i);
new ThreadedEchoHandler(incoming, i).start();
i++;
}
}
catch (Exception e)
{ System.out.println(e);
}
}
}
class ThreadedEchoHandler extends Thread
{ private Socket incoming;
private int counter;
public ThreadedEchoHandler(Socket i, int c)
{ incoming = i; counter = c; }
public void run()
{ try
{ BufferedReader in = new BufferedReader
(new InputStreamReader(incoming.getInputStream()));
PrintWriter out = new PrintWriter
(incoming.getOutputStream(), true /* autoFlush */);
out.println( "Hello! Enter BYE to exit." );
boolean done = false;
while (!done)
{ String str = in.readLine();
if (str == null) done = true;
else
{ out.println("Echo (" + counter + "): " + str);
if (str.trim().equals("BYE"))
done = true;
}
}
incoming.close();
}
catch (Exception e)
{ System.out.println(e);
}
}
}
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