简体   繁体   中英

How to create a socket that constantly listen from the Server in Java?

I'm doing a kind of Clock using Sockets with Java however I need that my client can interact with the Server changing the time. My main problem is: if I add any code for listen the Client, the Server Stop. I think I could use a thread or a async function nevertheless I'm totally new in Java and I don't know how to manipulate it.

These are my current codes:

server.java

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class server {

public static void main(String[] args) throws IOException,
        ClassNotFoundException {

    ServerSocket ss = new ServerSocket(2000);
    Timer data = new Timer();

    while (true) {

        Socket s = ss.accept();

        ArrayList<Integer> time = new ArrayList<Integer>();

        data.updateTime();

        time.add(data.getHour());
        time.add(data.getMinute());
        time.add(data.getSecond());

        System.out.println(time.get(0) + ":" + time.get(1) + ":"
                + time.get(2));

        try {
            ObjectOutputStream oos = new ObjectOutputStream(
                    s.getOutputStream());
            oos.writeObject(time);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(1000); // 1000 milliseconds is one second.
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }
}
}

Timer.java

import java.util.Random;

public class Timer {
private int hour;
private int minute;
private int second;

public Timer() {
    this.hour = randInt(0, 23);
    this.minute = randInt(0, 59);
    this.second = randInt(0, 59);
}

public void changeTime(int hour, int minute, int second) {
    this.hour = hour;
    this.minute = minute;
    this.second = second;
}

public static int randInt(int min, int max) {

    // NOTE: Usually this should be a field rather than a method
    // variable so that it is not re-seeded every call.
    Random rand = new Random();

    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}

private void updateHour() {
    if (this.hour == 23)
        this.hour = 0;
    else
        this.hour++;
}

private void updateMinute() {
    if (this.minute == 59)
        this.minute = 0;
    else
        this.minute++;
}

private void updateSecond() {
    if (this.second == 59)
        this.second = 0;
    else
        this.second++;
}

public int getHour() {
    return hour;
}

public int getMinute() {
    return minute;
}

public int getSecond() {
    return second;
}

public void updateTime() {
    this.updateSecond();

    if (this.second == 0) {
        this.updateMinute();
        if (this.minute == 0)
            this.updateHour();
    }
}
}

And this is the Event Click where I'm trying to send the Data:

    public void actionPerformed(ActionEvent arg0) {
    if (arg0.getSource() == startButton) {
        Socket s;
        try {
            s = new Socket("localhost", 2000);
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    in, textField1.getText()));
            out = new BufferedOutputStream(out);
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(out,
                    textField1.getText()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }// we try to connect
    }
}

I'd like to know if any of you know what kind of Code I should add in the Server to continue sending the Time randomly created and to wait if there is any message from the client and if there is a message to change the time with the new one. Thanks in Advance for your help, and so sorry if it's a basic question but I'm really new with Sockets and Java.

You can create a class to store your timer.

public class MyTimer(){
    private Timer t;
    public MyTimer(Timer t){
        this.t = t;
    }

    public synchronized Timer getTimer(){
        return t;
    }

    public synchronized void setTimer(Timer t){
        this.t = t;
    }
}

And in the server, you need to use an object from this class.

final MyTimer myTimer = new MyTimer(new Timer());

In the first line in while loop, you can get the timer inside the myTimer to your data variable.

Timer data = myTimer.getTimer();

Before the while loop, start a new Thread to listen to the client so that you can update the timer in myTimer object.

new Thread(new Runnable(){
    public void run(){
        while(true){
            //Listen to the client if there is new time available
            //get new timer to a variable (here, newData)
            myTimer.setTimer(newData);
        }
    }
}).start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM