I'm trying to write a multi-threaded server application. The server is just going to be the same computer as the client just because its more convenient to write that way. I have a book, "Absolute Java" to go by, but I can't figure out what is wrong. The amount of code is very small so I'll just post all of it.
Client:
package stuff;
import java.net.*;
import java.io.*;
public class Client1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
int port = 4444;
String hostname = "localhost";
Socket connectionSock = new Socket(hostname, port);
BufferedReader serverInput =
new BufferedReader(new InputStreamReader(connectionSock.getInputStream()));
DataOutputStream serverOutput =
new DataOutputStream(connectionSock.getOutputStream());
serverOutput.writeBytes("Print this message Mr. server");
}catch (Exception e){}
}
}
Server:
package stuff;
import java.net.*;
import java.io.*;
public class Server extends Thread {
/**
* @param args
*/
Socket connection;
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
ServerSocket serverSock = new ServerSocket(4444);
while(true)
{
Socket connectionSock = serverSock.accept();
System.out.println("Client connection accepted.");
Server handler = new Server(connectionSock);
handler.start();
}
}catch(Exception e){}
}
public Server(Socket connectionSocket)
{
connection = connectionSocket;
}
public void run()
{
try{
BufferedReader clientInput =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
DataOutputStream clientOutput = new DataOutputStream(connection.getOutputStream());
String test = clientInput.readLine();
System.out.println("read in " + test);
}catch(Exception e){}
}
}
Its supposed to be fairly easy to set up something like what I've attempted above, so perhaps I haven't gotten the concepts down. But I think I do. One thing I don't understand is how can we initially ask the server which port we should try to connect to (the one we initially connect to before the server spins us off to another port)? Or do we just have to know that in advance?
Also, is there something wrong with how I'm trying to make the application multi-threaded? Thats what I thought was wrong at first, but when I run the program, the run method is invoked, it just never reads in the text that the client sends.