MyChatSocket.java: Difference between revisions
Appearance
Created page with "Back to Into Java - Part XXIII <PRE> </PRE> Category:Languages Articles" |
|||
(8 intermediate revisions by 2 users not shown) | |||
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> | </PRE> | ||
[[Category:Into Java]] | |||
[[Category: |
Latest revision as of 19:16, 13 June 2020
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) {} } } }