如何使服务器在按钮单击时向客户端发送消息

时间:2015-02-22 19:05:32

标签: java client server

我有一个客户端和一个服务器。当客户端连接到服务器时,服务器会向客户端发送消息。 如果用户单击“新消息”按钮,我希望服务器向客户端发送新消息。 我怎样才能做到这一点?

我的代码(我已删除所有try-Catch)

客户端:

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();    
        }  
    }

处理程序:

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();
   }

服务器:

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();                                 
        }
    }

1 个答案:

答案 0 :(得分:2)

你想要得到什么信息?随机消息或预设的内容?正在使用Gui?

如果您使用gui并尝试收到消息,我希望您可以执行类似

的操作
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();    
    }  
}

您的后端客户端可能会看起来像这样

这是一个样本,所以撕开它并使用你想要的东西:

// 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);
}
  }
}

您的后端服务器应该看起来像这样

/* 
* 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);
}
  }
}