MyChatSocket.java: Difference between revisions
Appearance
mNo edit summary |
m Ak120 moved page Into Java - Part XXIII:MyChatSocket.java to MyChatSocket.java |
(No difference)
|
Revision as of 16:58, 22 February 2018
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 occured } } } 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) {} } } }