[790] in java-interest

home help back first fref pref prev next nref lref last post

Re: Non-blocking read on Socket?

daemon@ATHENA.MIT.EDU (Simon Spero)
Thu Jul 20 03:40:26 1995

Date: Wed, 19 Jul 1995 23:08:16 -0700 (PDT)
From: Simon Spero <ses@tipper.oit.unc.edu>
To: Pat Niemeyer <pat@icon-stl.net>
Cc: java-interest@java.Eng.Sun.COM
In-Reply-To: <Pine.BSI.3.91.950719114742.16433A-100000@server.icon-stl.net>

Here's an example of a simple class which uses threads to copy data in 
both directions over a socket- run it with a hostname and port, and it 
opens a connection - just a port and it waits to be talked to. Use it to 
talk to itself, imap , http, or if you have the right keyboard, you can 
do your own telnet negotiations. hours of fun for all the family 

Simon
p.s. 
 This program runs fine under java, but core-dumps java_g -t. Is there a 
bug in the threadDeath code in java_g?

/* Example of using threads to read and write from a socket */

import java.util.*;
import java.io.*;
import net.*;

class CopyThread extends Thread {
  InputStream in;
  OutputStream out;
  CopyThread partner;
  CopyThread(InputStream i, OutputStream o) {
    in = i; out = o; partner = null;
  }
  void setPartner(CopyThread p) {
    partner = p;
  }
  public void run() {
    try {
      while(true) {
	int c;
	c = in.read();
	if(c <0) {
	  break;
	}
	out.write(c);
	Thread.yield();
      }
      System.err.println(getName() + ": hit eof - killing partner");
      partner.stop();
    } finally {
      System.err.println(getName() + ": closing output");
      out.close();
    }
  }
}

class CopyDemo {
  static void copy(InputStream ia, OutputStream oa, InputStream ib,
		   OutputStream ob) {
    CopyThread a_thread=new CopyThread(ia,oa);
    a_thread.setName("a_thread");
    CopyThread b_thread=new CopyThread(ib,ob);
    b_thread.setName("b_thread");
    a_thread.setPartner(b_thread);
    b_thread.setPartner(a_thread);
    a_thread.start();
    b_thread.start();
    a_thread.join();
    b_thread.join();
  }
  static int atoi(String s) {
    return (new Integer(s)).intValue();
  }
  public static void main(String argv[]) {
    Socket s = null;
    if(argv.length == 1) {
      int port = atoi(argv[0]);
      Socket accepter = new Socket(true);
      accepter.bindToPort(new InetAddress("0.0.0.0"),port);
      accepter.listen(128);
      s= accepter.accept();
    } else {
      s = new Socket(argv[0],atoi(argv[1]));
    }
    copy(System.in,s.outputStream,s.inputStream,System.out);
  }
}


-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com

home help back first fref pref prev next nref lref last post