I have a Server-Client program in Java where,in my Server UI I have two JLabel
,when I Click on my 1st JLabel
message is going to 1st Client but when I click it again message is not going to the client. Can someone point me out whats the mistake in my code?
//SERVER CODE
void connect_clients()
{
try {
ServerSocket listener = new ServerSocket(7700);
jButton1.setText("Server Running!");
jButton1.setEnabled(false);
try {
while (true) {
socket = listener.accept();
try {
clientIP = socket.getLocalAddress().getHostName();
}
catch(Exception e){}
}
}
catch(Exception e){}
}
catch(IOException ex)
{
}
}
}
private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {
PrintWriter out;
try {
out = new PrintWriter(socket.getOutputStream(), true);
out.println("pc2");
} catch (IOException ex) {
Logger.getLogger(third_frame.class.getName()).log(Level.SEVERE, null, ex);
}
}
//client code
void connect_server()
{
try {
// TODO code application logic here
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
s = new Socket(serverAddress, 7700);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
System.out.println(answer);
answer = null;
}
catch (IOException ex) {
Logger.getLogger(client_form.class.getName()).log(Level.SEVERE, null, ex);
}
}
NOTE: Socket
is declared globally in both Server and Client.
Client code doesnt have a loop.
On String answer = input.readLine(); the client waits for the message to receive. Once it receives the text from server the clients execution is done.
Client is not written to receive all the message from server.
So if you look back the Server-Client paradigm, the server listens to the port actively and once the client requests something from server. It process the request.
On the other hand , Client doesnt have to listen actively on whats going on at the server which contradicts the fundamental idea of why Client exist.