@newbie_at_code

Как связать таймеры друг с другом?

Доброго времени суток!
Есть клиент-сервер, когда клиент подключается к серверу открываются фреймы, 1-ый с отображением значения таймера, 2-ой с кнопками для таймера. Соответственно есть код таймера, как связать клиентов так, что бы когда к серверу подключался новый клиент, он видел текущее значение таймера ?
Код клиента:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class keks_client {

    /**
     * 
     * @param args
     * @throws InterruptedException
     * @throws IOException 
     * @throws NumberFormatException 
     */
    public static void main(String[] args) throws InterruptedException, NumberFormatException, IOException {
		int serverPort = 0;
		String address = null;
	
		BufferedReader keyboard = new BufferedReader(new InputStreamReader(System. in ));
        System.out.println("Type address of the server: ");
        address = keyboard.readLine();
        System.out.println("Type port of the server: ");
        serverPort = Integer.parseInt(keyboard.readLine());
   
        try(Socket socket = new Socket(address, serverPort);  
                BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
                DataOutputStream oos = new DataOutputStream(socket.getOutputStream());
                DataInputStream ois = new DataInputStream(socket.getInputStream()); )
        {
            System.out.println("Client connected to socket.");
            System.out.println();
            System.out.println("Client writing channel = oos & reading channel = ois initialized.");            

                while(!socket.isOutputShutdown()){

                    if(br.ready()){
                     
            System.out.println("Client start writing in channel...");
            Thread.sleep(1000);
            String clientCommand = br.readLine();
           
            oos.writeUTF(clientCommand);
            oos.flush();
            System.out.println("Client sent message " + clientCommand + " to server.");
            Thread.sleep(1000);
            if(clientCommand.equalsIgnoreCase("quit")){
                System.out.println("Client kill connections");
                Thread.sleep(2000);
        
                if(ois.read() > -1)     {   
                    System.out.println("reading...");
                    String in = ois.readUTF();
                    System.out.println(in);
                            }
             
                break;              
            }
        
            System.out.println("Client sent message & start waiting for data from server...");          
            Thread.sleep(2000);
        
            if(ois.read() > -1)     {   

                     
            System.out.println("reading...");
            String in = ois.readUTF();
            System.out.println(in);
                    }           
                }
            }

            System.out.println("Closing connections & channels on clentSide - DONE.");

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


Код сервера:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author mercenery
 *
 */
public class keks_fabrics{

    static ExecutorService executeIt = Executors.newFixedThreadPool(2);

    /**
     * @param args
     * @throws IOException 
     * @throws NumberFormatException 
     */
    public static void main(String[] args) throws NumberFormatException, IOException {
		int serverPort = 0;

		BufferedReader keyboard = new BufferedReader(new InputStreamReader(System. in ));
        System.out.println("Type port of the server: ");
        serverPort = Integer.parseInt(keyboard.readLine());
        try (ServerSocket server = new ServerSocket(serverPort);
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
            System.out.println("Server socket created, command console reader for listen to server commands");

            while (!server.isClosed()) {

                if (br.ready()) {
                    System.out.println("Main Server found any messages in channel, let's look at them.");

                    String serverCommand = br.readLine();
                    if 
                    (serverCommand.equalsIgnoreCase("start"));
                    System.out.println("start stopwatch...");
                    Stopwatch Stopwatch = new Stopwatch();
                    Stopwatch.setVisible(true);
                    { 
                    }
                }

                Socket client = server.accept();

                executeIt.execute(new MonoThreadClientHandler(client));
                System.out.print("Connection accepted.");
            }

            executeIt.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }}


Подскажите, как это возможно реализовать?

UPD
Код Stopwatch:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Stopwatch implements ActionListener{


		JButton button = new JButton("knopka");
		JFrame frame_timer = new JFrame();
		JFrame frame = new JFrame();
		JButton startButton = new JButton("start");
		JButton resetButton = new JButton("reset");
		JLabel timeLabel = new JLabel();
		int elapsedTime = 0;
		int seconds =0;
		int minutes =0;
		int hours=0;
		boolean started = false;
		String seconds_string = String.format("%02d", seconds);
		String minutes_string = String.format("%02d", minutes);
		String hours_string = String.format("%02d", hours); 
	
		Timer timer = new Timer(1000, new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				
				elapsedTime=elapsedTime+1000;
				hours = (elapsedTime/3600000);
				minutes = (elapsedTime/60000)%60;
				seconds = (elapsedTime/1000)%60;
				seconds_string = String.format("%02d", seconds);
				minutes_string = String.format("%02d", minutes);
				hours_string = String.format("%02d", hours);
				
				timeLabel.setText(hours_string+":"+minutes_string+":"+seconds_string);
			}
			
			
		});
		
		public Stopwatch(){
			
			timeLabel.setText(hours_string+"-"+minutes_string+"-"+seconds_string);
			timeLabel.setBounds(100,100,200,100);
			timeLabel.setFont(new Font("Verdana",Font.PLAIN,35));
			timeLabel.setBorder(BorderFactory.createBevelBorder(1));
			timeLabel.setOpaque(true);
			timeLabel.setHorizontalAlignment(JTextField.CENTER);
	
			startButton.setBounds(100,100,200,50);
			startButton.setFont(new Font("Calibri",Font.PLAIN,20));
			startButton.setFocusable(false);
			startButton.addActionListener(this);
			
			resetButton.setBounds(100,150,200,50);
			resetButton.setFont(new Font("Calibri",Font.PLAIN,20));
			resetButton.setFocusable(false);
			resetButton.addActionListener(this);
			
			frame.add(startButton);
			frame.add(resetButton);
			frame.add(timeLabel);
			
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setSize(420,420);
			frame.setLayout(null);
			frame.setVisible(true);
			
			frame_timer.add(timeLabel);
			frame_timer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame_timer.setSize(420,420);
			frame_timer.setLayout(null);
			frame_timer.add(timeLabel);
			frame_timer.setVisible(true);
		}


		@Override
		public void actionPerformed(ActionEvent e) {
			
			if(e.getSource()==startButton) {
				start();
				if(started==false) {
					started=true;
					startButton.setText("stop");
					start();
				}
				else {
					started=false;
					startButton.setText("continue");
		
					stop();
				}
			}

						if(e.getSource()==resetButton){
				started=false;
				startButton.setText("start");
				reset(); }
				}
	
		
void start() {
	timer.start();
	}
void stop() {
	timer.stop();
}
void reset() {
	timer.stop();
	elapsedTime=0;
	seconds=0;
	minutes=0;
	hours=0;
	seconds_string = String.format("%02d", seconds);
	minutes_string = String.format("%02d", minutes);
	hours_string = String.format("%02d", hours);
	timeLabel.setText(hours_string+":"+minutes_string+":"+seconds_string);
}


public void setVisible(boolean b) {
	// TODO Auto-generated method stub
	
}


public static Object getDelay() {
	// TODO Auto-generated method stub
	return null;
}
}
  • Вопрос задан
  • 181 просмотр
Пригласить эксперта
Ответы на вопрос 1
xez
@xez Куратор тега Java
TL Junior Roo
Сделайте один общий сервис, в котором будет жить сам таймер и в котором будут методы для управлением таймером и получению текущего состояния.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы