更新从java中的服务器接收数据

时间:2014-05-28 07:16:47

标签: java networking tcp

我有一个程序从服务器接收一些数据并在客户端显示它们(图形而不是控制台),但是当我的程序获取新数据时,我应该再次运行客户端以加载新数据。

问题是如何在客户端运行时显示数据?

我只想澄清我的问题

这就是我在服务器端所做的事情

private void transferData() {
    OutputStream outputStream = null;
    try {
        Socket connection = serverSocket.accept();
        outputStream = connection.getOutputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String data;
    for (Bubble bubble : field.getBubbles()) {
        data = bubble.getX() + " " + bubble.getY() + " " + bubble.getRadius() + " " + bubble.getColor().getRed() + " " + bubble.getColor().getGreen() + " " + bubble.getColor().getBlue() + " ";
        try {
            if (outputStream != null) {
                outputStream.write(data.getBytes());
            }
        } catch (IOException e) {
            System.err.println(prefix + e);
        }
    }
}

public void run() {
    while (isAlive) {
        transferData();
    }
}

和客户端

public void run() {
    if (connection == null || !connection.isConnected()) {
        System.out.println(prefix + "connecting to server failed!");
        return;
    }
    InputStream inputStream;
    try {
        byte[] inputInformation = new byte[2048];
        inputStream = connection.getInputStream();
        inputStream.read(inputInformation);
        String s = new String(inputInformation);
        System.out.println(s);
        String[] y = s.split("\\s");
        intData = new int[6];
        for (int j = 0; j < y.length / 6; j++) {
            for (int i = 0; i < 6; i++) {
                intData[i] = Integer.parseInt(y[6 * j + i]);
            }
            //add something to gui
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    while (isAlive) {
            //do sth
        repaint();
        try {
            //it's obvious, refresh rate !
            Thread.sleep(1000 / REFRESH_RATE);
        } catch (InterruptedException e) {
            System.err.println(prefix + e);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您的问题并不是很清楚,但基本上您应该有一个不断接收数据的线程(即读取与服务器连接的套接字),与GUI线程同步:当第一个线程收到消息时,它与之通信GUI线程为了更新它,然后再回来再次读取套接字。

示例:

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class Test {

    public static void main(String args[]) {
        GUIThread gui = new GUIThread(); //create gui thread
        //create connection thread (with reference to gui GUI thread)
        ConnectionThread c = new ConnectionThread(gui);
        //start to run both threads
        gui.start();
        c.start();

    }
}

class GUIThread extends Thread {

    private final JFrame f;
    private final JTextArea t;

    public GUIThread() {
        f = new JFrame(); //gui main window
        t = new JTextArea("Waiting data...\n", 32, 64); //to display the data
        f.add(t);
        f.pack();
    }

    @Override
    public void run() { //method running on a separated thread
        f.setVisible(true); //show the gui
    }

    synchronized public void showData(String data) { //method called by the ConnectionThread
        t.append(data + '\n'); //to update the gui to show the data
    }


}

class ConnectionThread extends Thread {

    private final GUIThread gui;

    public ConnectionThread(GUIThread gui) {
        this.gui = gui; //store reference to the gui thread
    }

    @Override
    public void run() {
        try {
            Socket s = new Socket("www.google.com", 80); //open a client connection
            BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream())); //to read
            OutputStreamWriter writer = new OutputStreamWriter(s.getOutputStream()); //to write (only if you need)
            String request = "GET / HTTP/1.1\n\n"; //a string to send to the server
            writer.write(request, 0, request.length()); //in order to receive some data back (to simulate your situation)
            writer.flush();
            String line;
            while ((line = reader.readLine()) != null) { //read data from the connection until the connection is closed
                gui.showData(line); //update the gui
            }
        } catch (IOException ex) {
            //eventually exception handling
            System.err.println(ex);
        }

    }
}