I am building a simple client/server application using java sockets and experimenting with the ObjectOutputStream etc.
I have been following the tutorial at this url
Probably you'll like to learn the most basic first.
Here's a sample I have just coded.
It start a server, that attends only ONE client, and it sends an object and die.
When the user ( you ) press enter, a new client is created, it connects to the previously created server and read the object that server will send.
No exception is handled here. Just to make things simpler, but this is NOT the way exception should be handled.
When you understand all the concepts here, it will be easier to understand those in the tutorial.
import java.io.*;
import java.net.*;
import java.util.*;
public class SimpleServer implements Runnable {
// Creates the server, send a "date" and die.
public void run() {
try {
ServerSocket server = new ServerSocket( 8090 );
Date creationDate = new Date();
System.out.println("(Server) Server is ready "
+ "and running at " + creationDate );
Socket uniqueClient = server.accept();
// We will write using this "chained" object.
ObjectOutputStream out = new ObjectOutputStream(
uniqueClient.getOutputStream());
out.writeObject( creationDate );
// close all, at this point forget about the exceptions.
// this is lesson #1
out.close();
uniqueClient.close();
server.close();
System.out.println("(Server) The server is down");
}catch( IOException ioe ) {}
}
public static void main ( String [] args ) throws IOException ,
ClassNotFoundException {
Thread serverThread = new Thread( new SimpleServer() );
serverThread.start(); // start the server thread ... doh..
System.out.println("(Client) Press enter when you want "+
" to connect to the server...");
Scanner scanner = new Scanner( System.in );
scanner.nextLine();
Socket client = new Socket("localhost", 8090 );
// Read from this object.
ObjectInputStream in = new ObjectInputStream( client.getInputStream() );
Date date = ( Date ) in.readObject();
System.out.println("(Client) Current time is: " + new Date() );
System.out.println("(Client) Object read from server : " + date );
in.close();
client.close();
}
}
I hope this helps.