I am trying to write a program, where Client is sending a string to a Server using output stream. Server would see what string it is, it compares it to a conditional, and then sends it back to the client and displays a message on client's side. I would like to understand how it works, and what is wrong with my code so far. Once I get it I will implement it with JavaFX.
Client
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class MyClient {
static Socket socket;
static int clientNo;
static DataOutputStream toServer;
static DataInputStream fromServer;
public static void main(String[] args) {
try{
socket = new Socket("localhost", 8888);
System.out.println("Client connected to the server");
fromServer = new DataInputStream(socket.getInputStream());
toServer = new DataOutputStream(socket.getOutputStream());
toServer.writeBytes("listAll");
toServer.flush();
System.out.println("Sending string to the ServerSocket");
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}
Server
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class MyServer {
static final int PORT = 8888;
static ServerSocket serverSocket;
static Socket socket;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Server started at " + new Date());
System.out.println("Server on PORT: " + PORT + " is open");
System.out.println("Server is ready for multiple clients!");
System.out.println("Waiting for request...");
while(true){
socket = MyServer.serverSocket.accept();
new Thread(new HandleClient(MyClient.socket)).start();
}
} catch (IOException ex) {
System.err.println("Server Error: " + ex.getMessage());
}
}
}
Thread
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class HandleClient implements Runnable {
private Socket socket;
public static int clientNo = 1;
public static int condition;
static DataInputStream input ;
static DataOutputStream output;
static String message;
public HandleClient(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
switch (condition) {
case 1:
break;
case 2:
System.out.println("list all");
break;
case 3:
break;
default:
System.out.println("Client #" + clientNo + " connected!");
clientNo++;
try {
input = new DataInputStream(socket.getInputStream());
output = new DataOutputStream(socket.getOutputStream());
message = input.readUTF();
System.out.println(message);
if("listAll".equals(message)){
HandleClient.condition = 2;
new Thread(new HandleClient(socket)).start();
}
} catch (IOException ex) {
System.err.println("One of the clients disconnected");
}
break;
}
}
}
I really appreciate any help! I understand I might have some code missing to send the response back to the client? Please let me know if the direction I am going is good.