Java Network
Java Network
When creating a socket, you pass in the hostname and port number.
The java.net.Socket constructor does the gethostbyname() and the socket() system call,
sets up the server's sockaddr_in structure, and executes the connect() call.
All you have to do is catch the errors, which are subclassed from the familiar
IOException.
You can both read and write on the same Socket.
Server Sockets
InetAddress
The InetAddress is mainly used for looking up a host's address name or number.
It is also possible to obtain the address at the other end of a connection.
The InetAddress object represents the Internet address of a given computer or host.
There are no public constructors, you can obtain an InetAddress object by calling the
static byName method, passing in either a hostname like wwww.iDevelopment.info or a
network address as a String, like "12.4.234.11".
Here is an example of how to extend a very simple client-server demo program into a
fully functioning (but simple) Chat Client/Server package. There are five stages involved:
Step 1: A simple server that will accept a single client connection and display
everything the client says on the screen. If the client user types ".bye", the client and the
server will both quit.
Step 2: A server as before, but this time it will remain 'open' for additional
connection once a client has quit. The server can handle at most one connection at a time.
Step 3: A server as before, but this time it can handle multiple clients
simultaneously. The output from all connected clients will appear on the server's screen.
Step 4: A server as before, but this time it sends all text received from any of the
connected clients to all clients. This means that the server has to receive and send, and the
client has to send as well as receive
Step 5: Wrapping the client from step 4 into a very simple GUI interface but not
changing the functionality of either server or client. The client is implemented as an
Applet, but a Frame would have worked just as well (for a stand-alone program).
The Simple Client corresponding to the previous server (and to step 2 and step 3 servers
as well):
import java.net.*;
import java.io.*;
import java.net.*;
import java.io.*;
if (args.length == 0)
port = DEFAULT_PORT;
else {
try {
port= Integer.parseInt(args[0]);
if (port < 0 || port > 65535)
throw new NumberFormatException();
}
catch (NumberFormatException e) {
TextIO.putln("Illegal port number, " + args[0]);
return;
}
}
try {
listener = new ServerSocket(port);
TextIO.putln("Listening on port " + listener.getLocalPort());
connection = listener.accept();
listener.close();
incoming = new TextReader(connection.getInputStream());
outgoing = new PrintWriter(connection.getOutputStream());
outgoing.println(HANDSHAKE);
outgoing.flush();
messageIn = incoming.getln();
if (! messageIn.equals(HANDSHAKE) ) {
throw new IOException("Connected program is not CLChat!");
}
TextIO.putln("Connected. Waiting for the first message.\n");
}
catch (Exception e) {
TextIO.putln("An error occurred while opening connection.");
TextIO.putln(e.toString());
return;
}
try {
while (true) {
TextIO.putln("WAITING...");
messageIn = incoming.getln();
if (messageIn.length() > 0) {
// The first character of the message is a command.
// If the command is CLOSE, then the connection
// is closed. Otherwise, remove the command
// character from the message and procede.
if (messageIn.charAt(0) == CLOSE) {
TextIO.putln("Connection closed at other end.");
connection.close();
break;
}
messageIn = messageIn.substring(1);
}
TextIO.putln("RECEIVED: " + messageIn);
TextIO.put("SEND: ");
messageOut = TextIO.getln();
if (messageOut.equalsIgnoreCase("quit")) {
// User wants to quit. Inform the other side
// of the connection, then close the connection.
outgoing.println(CLOSE);
outgoing.flush(); // Make sure the data is sent!
connection.close();
TextIO.putln("Connection closed.");
break;
}
outgoing.println(MESSAGE + messageOut);
outgoing.flush(); // Make sure the data is sent!
if (outgoing.checkError()) {
throw new IOException("Error occurred while transmitting message.");
}
}
}
catch (Exception e) {
TextIO.putln("Sorry, an error has occurred. Connection lost.");
TextIO.putln(e.toString());
System.exit(1);
}
} // end main()
import java.net.*;
import java.io.*;
if (args.length == 0) {
TextIO.putln("Usage: java SimpleClient <computer-name> [<port>]");
return;
}
computer = args[0];
if (args.length == 1)
port = DEFAULT_PORT;
else {
try {
port= Integer.parseInt(args[1]);
if (port <= 0 || port > 65535)
throw new NumberFormatException();
}
catch (NumberFormatException e) {
TextIO.putln("Illegal port number, " + args[1]);
return;
}
}
try {
TextIO.putln("Connecting to " + computer + " on port " + port);
connection = new Socket(computer,port);
incoming = new TextReader(connection.getInputStream());
outgoing = new PrintWriter(connection.getOutputStream());
outgoing.println(HANDSHAKE);
outgoing.flush();
messageIn = incoming.getln();
if (! messageIn.equals(HANDSHAKE) ) {
throw new IOException("Connected program is not CLChat!");
}
TextIO.putln("Connected. Enter your first message.\n");
}
catch (Exception e) {
TextIO.putln("An error occurred while opening connection.");
TextIO.putln(e.toString());
return;
}
try {
while (true) {
TextIO.put("SEND: ");
messageOut = TextIO.getln();
if (messageOut.equalsIgnoreCase("quit")) {
// User wants to quit. Inform the other side
// of the connection, then close the connection.
outgoing.println(CLOSE);
outgoing.flush();
connection.close();
TextIO.putln("Connection closed.");
break;
}
outgoing.println(MESSAGE + messageOut);
outgoing.flush();
if (outgoing.checkError()) {
throw new IOException("Error occurred while transmitting message.");
}
TextIO.putln("WAITING...");
messageIn = incoming.getln();
if (messageIn.length() > 0) {
// The first character of the message is a command.
// If the command is CLOSE, then the connection
// is closed. Otherwise, remove the command
// character from the message and procede.
if (messageIn.charAt(0) == CLOSE) {
TextIO.putln("Connection closed at other end.");
connection.close();
break;
}
messageIn = messageIn.substring(1);
}
TextIO.putln("RECEIVED: " + messageIn);
}
}
catch (Exception e) {
TextIO.putln("Sorry, an error has occurred. Connection lost.");
TextIO.putln(e.toString());
System.exit(1);
}
} // end main()