Jump to content

MyChatSocket.java: Difference between revisions

From EDM2
Ak120 (talk | contribs)
mNo edit summary
Ak120 (talk | contribs)
wrong content type
Line 1: Line 1:
<PRE>
import java.net.*;
import java.io.*;


public class MyChatSocket extends Socket implements Runnable {
    protected ChatApplet    owner;
    protected BufferedReader bis;
    public MyChatSocket(ChatApplet o, String address,
                    int port) throws java.io.IOException {
        super(address, port);
        owner = o;
        bis = new BufferedReader(
                new InputStreamReader(
                    this.getInputStream()));
        new MyTimer(this);
        Thread thread = new Thread(this);
        thread.start();
    }
    public void run() {
        String        line;
        while (owner.isConnected) {
            try {
                bis.readLine(); // skip first line
                while ((line = bis.readLine()) != null) {
                    owner.setMessage(line);
                }
            } catch (IOException e) {
                if (owner.isConnected) {
                    owner.setMessage(
                        "Error in socket's run method.");
                    owner.setMessage(e.getMessage());
                    owner.disconnect();
                } else ; // probably a disconnect occurred
            }
        }
    }
    class MyTimer extends Thread {
        public MyTimer(MyChatSocket s) {
            super(s);
            this.start();
        }
        /* Sends an empty message every 10th minute to
        * stay on-line. Recall that the server throws
        * you out if you are too quiet. */
        public void run() {
            try {
                while (true) {
                    this.sleep(600000L);
                    owner.sendMessage("");
                }
            } catch (Exception e) {}
        }
    }
}
</PRE>
[[Category:Into Java]]

Revision as of 10:15, 24 May 2020