I am writing a simple application which uses client-server architecture and communicates with sockets in Java. What I currently want to do is the following: - start the server - start the client which opens up a login frame - introduce username and password and when the OK button is clicked send an instance of the User class to the server, after which the server calls a method which verifies if the current input is a correct one by searching for this username-password pair in a database
My problem is the following: it is my first try with sockets in Java and I'm really confused where and what I need to do in order to make the communication happen as mentioned above.
Here is my server class given as an example to use for my application (didn't modify anything in it):
public class CMSocketServer implements Runnable {
private Socket connection;
private int ID;
public CMSocketServer(Socket connection, int ID) {
this.connection = connection;
this.ID = ID;
}
public void run() {
try {
readFromClient(connection);
} catch (Exception e) {
System.out.println(e);
} finally {
try {
connection.close();
} catch (IOException e){}
}
}
public void readFromClient(Socket client) throws IOException, ClassNotFoundException {
BufferedInputStream is = new BufferedInputStream(client.getInputStream());
InputStreamReader reader = new InputStreamReader(is);
StringBuffer process = new StringBuffer();
int character;
while((character = reader.read()) != 13) {
process.append((char)character);
}
System.out.println(process);
// wait 10 seconds
try {
Thread.sleep(10000);
} catch (Exception e){}
String time_stamp = new java.util.Date().toString();
String returnCode = "Single Socket Server responded at " + time_stamp + (char) 13;
sendMessage(client, returnCode);
}
private void sendMessage(Socket client, String message) throws IOException {
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(client.getOutputStream()));
writer.write(message);
writer.flush();
}
public static void main(String[] args) {
// Setting a default port number.
int portNumber = 2015;
int count = 0;
System.out.println("Starting the multiple socket server at port: " + portNumber);
try {
ServerSocket serverSocket = new ServerSocket(portNumber);
System.out.println("Multiple Socket Server Initialized");
//Listen for clients
while(true) {
Socket client = serverSocket.accept();
Runnable runnable = new CMSocketServer(client, ++count);
Thread thread = new Thread(runnable);
thread.start();
}
} catch (Exception e) {}
}
}
Then, he is my client class:
import java.io.*;
import java.net.*;
import java.sql.SQLException;
public class CSocketClient {
private String hostname = "localhost";
private int port = 2015;
Socket socketClient;
public CSocketClient(String hostname, int port)
{
this.hostname = hostname;
this.port = port;
}
public void connect() throws UnknownHostException, IOException {
System.out.println("Attempting to connect to " + hostname + ":" + port);
socketClient = new Socket(hostname, port);
System.out.println("Connection Established");
}
public void readResponse() throws IOException {
String userInput;
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(socketClient.getInputStream()));
System.out.println("Response from server:");
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
}
}
public void closeConnection() throws IOException {
socketClient.close();
}
public void writeMessage() throws IOException {
String time_stamp = new java.util.Date().toString();
// Please note that we placed a char(13) at the end of process...
// we use this to let the server know we are at the end
// of the data we are sending
String process = "Calling the Socket Server on " + hostname +
" port " + port +
" at " + time_stamp + (char) 13;
BufferedWriter stdOut = new BufferedWriter(
new OutputStreamWriter(socketClient.getOutputStream()));
stdOut.write(process);
// We need to flush the buffer to ensure that the data will be written
// across the socket in a timely manner
stdOut.flush();
}
public static void main(String arg[]) throws SQLException {
Login login = new Login();
BusinessLogic businessLogic = new BusinessLogic(login);
CSocketClient client = new CSocketClient("localhost", 2015);
try {
// conect to server
client.connect();
// write message to the server
client.writeMessage();
// read response from server
client.readResponse();
} catch (UnknownHostException e) {
System.err.println("Host unknown. Cannot establish connection");
} catch (IOException e) {
System.err.println("Cannot establish connection. Server may not be up."
+ e.getMessage());
}
}
}
And finally the control class which should send the object to the server:
public class BusinessLogic {
private final Login login;
/**
* Constructor instantiating needed classes
* @param login an instance of the login class
* @throws SQLException using classes connecting to a database sql exceptions can occur
*/
public BusinessLogic(Login login) throws SQLException
{
this.login = login;
login.addButtonListener(new ButtonListener());
}
/**
* Listener for the login button. Reads, verifies and provides the interface according to logged in user type.
*/
class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
try {
User user = new User(login.field1.getText(),login.field2.getText());
Socket socket = new Socket("localhost", 2015);
ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.writeObject(user);
outputStream.close();
} catch (IOException ex) {
Logger.getLogger(BusinessLogic.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
What am I doing wrong on the client side? And what should I do on the server side in order to receive the User object?
I would appreciate any help as a novice programmer.