user2939293
user2939293

Reputation: 813

How to make server send a message to client on button click

I have a client and a server. When client connects to server the server sends a message to the client. If the user clicks on button "New message" I want the server to send a new message to the client. How can I achieve that?

My code (I have removed all try-Catch)

Client:

private void getExpression() {
    Socket s = null;     

     s = new Socket(serverAddress, serverPort);                     
     out = new ObjectOutputStream(s.getOutputStream());             
     in = new ObjectInputStream(s.getInputStream());     

     while (true) {          
         Expression exp = (Expression) in.readObject();                    
         String message = exp.toString();
         expressionLabel.setText(message);  
      } 
    }

    public void newMessage() throws IOException {  
         //MAKE SERVER SEND NEW MESSAGE
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource().equals(newButton)) {
            newMessage();    
        }  
    }

Handler:

public class Handler extends Thread {    
    private Socket socket;              
    private String address;             

    public Handler (Socket s) {
        socket = s;
            address = socket.getInetAddress().getHostAddress();
    }

    @Override
    public void run() { 
        ObjectInputStream in = null;   
        ObjectOutputStream out = null;  

        out = new ObjectOutputStream(socket.getOutputStream());     
        in = new ObjectInputStream(socket.getInputStream());         

        out.writeObject(new Expression());               
        out.flush();
   }

Server:

private int port;

    public TestProgram(int port) {
        this.port = port;
        go();
    }

    public void go() {
        ServerSocket ss = null;    
        ss = new ServerSocket(port);   

        while (true) {
           Socket s = ss.accept();
           new Handler(s).start();                                 
        }
    }

Upvotes: 1

Views: 5317

Answers (1)

sinisterrook
sinisterrook

Reputation: 364

What message are you trying to get? A random message or something preset? Are using a Gui?

IF your using a gui and your trying to get a message I'd expect you to do something like

JButton newButton = new JButton("New Message");
newButton.addActionListener(this);
this.add(newButton);

public void newMessage() {
System.out.println(in.readObject().toString);
}


public void actionPerformed(ActionEvent ae) {
    if (ae.getSource().equals(newButton)) {
        newMessage();    
    }  
}

Your Back End Client Could Look Something Like This

This is a sample so tear it apart and use what you'd like:

// Client.java: The client sends the input to the server and receives
// result back from the server
import java.io.*;
import java.net.*;
import java.util.*;

public class Client
{
// Main method
public static void main(String[] args)
{
  // IO streams
  DataOutputStream toServer;
  DataInputStream fromServer;

try
{
  // Create a socket to connect to the server
  Socket socket = new Socket("localhost", 8000);

  // Create input stream to receive data
  // from the server
  fromServer = new DataInputStream(socket.getInputStream());

  // Create a output stream to send data to the server
  toServer = new DataOutputStream(socket.getOutputStream());

    Scanner scan= new Scanner (System.in);

  // Continuously send radius and receive area
  // from the server
  while (true)
  {
    // Read the m/s from the keyboard
    System.out.print("Please enter a speed in meters per second: ");
    double meters=scan.nextDouble();

    // Send the radius to the server
    toServer.writeDouble(meters);
      toServer.flush();


    // Convert string to double
    double kilometersPerHour = fromServer.readDouble();

    // Print K/h on the console
    System.out.println("Area received from the server is "
      + kilometersPerHour);
  }
}
catch (IOException ex)
{
  System.err.println(ex);
}
  }
}

Your Back End Server Should Look Something Like This

/* 
* Created by jHeck
*/
// Server.java: The server accepts data from the client, processes it
// and returns the result back to the client
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;

public class Server 
{
// Main method
public static void main(String[] args)
{ 
  try
{
  // Create a server socket
  ServerSocket serverSocket = new ServerSocket(8000);

  // Start listening for connections on the server socket
  Socket socket = serverSocket.accept();

  // Create data input and output streams
  DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());


  // Continuously read from the client and process it,
  // and send result back to the client
  while (true)
  {

    // Convert string to double
    double meters = inputFromClient.readDouble();

    // Display radius on console
    System.out.println("Meters received from client: "
      + meters);

    // Compute area
    double conversionToKilometers = (meters/1000)*3600;

    // Send the result to the client
    outputToClient.writeDouble(conversionToKilometers);

    //Create double formater
    DecimalFormat format = new DecimalFormat("0.00");
    String formatedCTK = format.format(conversionToKilometers);

    // Print the result to the console
    System.out.println("Kilometers per hour = "+ formatedCTK);
  }
}
catch(IOException ex)
{
  System.err.println(ex);
}
  }
}

Upvotes: 2

Related Questions