
/* THREADED simple talk TCP server */
/* can handle multiple CONCURRENT client connections */
/* newline is to be included at client side */

import java.lang.*;
import java.net.*;
import java.io.*;

public class tstalks {
	public tstalks() {}

    static public int destport = 5432;
    static public int bufsize = 512;
    static public boolean THREADING = true;

static public void main(String args[]) {
    ServerSocket ss;
    Socket s;
    try {
        ss = new ServerSocket(destport);
    } catch (IOException ioe) {
	System.err.println("can't create server socket");
	return;
    }
    System.err.println("server starting on port " + ss.getLocalPort());

    while(true) { // accept loop
		try {
		s = ss.accept();
		} catch (IOException ioe) {
			System.err.println("Can't accept");
			break;
		}
		System.err.println("New connection from port " + s.getPort());

		if (THREADING) {
			Talker talk = new Talker(s);
			(new Thread(talk)).start();
			s=null;
		} else {

			line_talker(s);

			try {
			s.close();
			}
			catch (IOException ioe) {
				System.err.println("bad socket close");
				return;
			}

		}

    } // accept loop

} // end of main

// fixed to read in units of complete lines.
// However, the stalk CLIENT does do buffering.

public static void line_talker(Socket s) {
		int port = s.getPort();
		InputStream istr;
		try { istr = s.getInputStream(); }
		catch (IOException ioe) {
			System.err.println("cannot get input stream");	// most likely cause: s was closed
			return;
		}

		InputStreamReader isr = new InputStreamReader(istr);

		BufferedReader br = new BufferedReader(isr);

		String buf; // = new byte[bufsize];
		int len;

		while (true) {	// read a line, print a line
			try {
					buf = br.readLine();
				}
				catch (IOException ioe) {
					System.err.println("readLine() failed");
					return;
				}

			if (buf == null) {
				//System.err.println("null string!");
				break;
			}

			//buf = buf.concat("\n");

			byte[] bbuf = buf.getBytes();
			System.out.println(buf);	// pick up newline here!
		} //while reading from s

		try {istr.close();}
		catch (IOException ioe) {
			System.err.println("bad stream close");
			return;
		}

		System.err.println("socket to port " + port + " closed");
		istr=null;
		try {
		s.close();
		}
		catch (IOException ioe) {
			System.err.println("bad socket close");
			return;
		}
} // line_talker

static class Talker implements Runnable {
	private Socket _s;

	public Talker (Socket s) {
		_s = s;
	}

	public void run() {
		line_talker(_s);
	} // run
}  // class Echoer

}
