I want to make use of ObjectInputStream and ObjectOutputStream to send data over Socket. I looked on the internet, but even with several explanation, i'm unable to fix my problem.
Here is my contructor succession:
public class Server {
//Entry point of the application
public static void main(String[] args) {
Integer port;
if(args.length<=0)
port=new Integer("3000"); // si pas d'argument : port 3000 par d�faut
else
port = new Integer(args[0]); // sinon il s'agit du num�ro de port pass� en argument
ClientListener server = new ClientListener(port); // instance de la classe principale
}
}
public ClientListener(Integer port) { // THIS IS THE MAIN THREAD
try
{
server = new ServerSocket(port.intValue()); // ouverture d'un socket serveur sur port
new IOCommande(this); // RUN IN ANOTHER THREAD
while (true) // attente en boucle de connexion (bloquant sur ss.accept)
{
new ClientSocketStream(server.accept(),this); // un client se connecte, un nouveau thread client est lanc�
}
}
catch (Exception e) {
//server.close();
}
}
public ClientSocketStream(Socket incomingClient, ClientListener ref) { // THIS IS NOT A THREAD
this.client = incomingClient;
this.server = ref;
//Ajout des IO et generation d'un UID
try{
out = new ClientOutputWriter(client.getOutputStream());
in = new ClientInputReader(((MessageReader)this),client.getInputStream());
// ajoute du client dans la liste
id = server.addClient(this);
}catch (IOException e){
e.printStackTrace();
}finally {// En cas de probl�me (que le client s'est d�connect�)
try {
server.removeClient(id);
client.close();
}catch(IOException e) {
}
}
}
public ClientInputReader(MessageReader client, InputStream in) throws IOException { //THIS IS A THREAD
this.client = client;
try {
this.in = new ObjectInputStream(in);
}catch(Exception e){
e.printStackTrace();
}
this.runtime = new Thread(this);
this.runtime.start();
}
public ClientOutputWriter(OutputStream out) throws IOException { //THIS IS NOT A THREAD
this.out = new ObjectOutputStream(out);
}
Please suppose that the socket is fully working, so i'm able to connect using Telnet.
So i'm stuck when instanciating the ObjectInputStream, in the ClientInputReader class. The constructor appears to be blocking,and i'm unable to make a correct use of this.
Instead of testing using telnet, try to create another runnable project. Don't forget to Declare the objectOutputStream before the ObjectInputStream and do something like the following :
public class TestClient {
//Entry point of the application
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 3000);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
out.writeObject(new Message("test"));
Message msg = (Message)in.readObject();
socket.close();
}catch(Exception e){}
}
}
Your client isn't constructing an ObjectOutputStream
, so your ObjectInputStream
constructor is blocking for reasons explained in the Javadoc.