
/* simple talk TCP server */
/* newline is to be included at client side */

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

public class server {


    static public int destport = 5431;
    static public int bufsize = 512;

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.out.println("Waiting on port " + destport);

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

		InputStream istr;
		try { istr = s.getInputStream(); }
		catch (IOException ioe) {
			System.err.println("What the heck?!?");
			return;
		}

		OutputStream ostr;
		try { ostr = s.getOutputStream(); }
		catch (IOException ioe) {
			System.err.println("What the heck?!?");
			return;
		}

		System.err.println("New connection from <" + 
		    s.getInetAddress().getHostAddress() + "," + s.getPort() + ">");
		byte[] buf = new byte[bufsize];
		int len;
		
		// read 
			try {
				len = istr.read(buf, 0, bufsize);
			}
			catch (SocketTimeoutException ste) {
				System.out.println("socket timeout");
				continue;
			}
			catch (IOException ioe) {
				System.err.println("bad read");
				break;	// probably a socket ABORT; treat as a close
			}
			if (len == -1) break;
			String str = new String(buf, 0, len);
			System.out.println(str);

		// write

			String sa = "artichokes";
			byte[] buf2 = sa.getBytes();
			try {
				ostr.write(buf2);
			}
			catch (IOException ioe) {
				System.out.println("bad write");
			}
		// read 
			try {
				len = istr.read(buf, 0, bufsize);
			}
			catch (SocketTimeoutException ste) {
				System.out.println("socket timeout");
				continue;
			}
			catch (IOException ioe) {
				System.err.println("bad read");
				break;	// probably a socket ABORT; treat as a close
			}
			if (len == -1) break;
			str = new String(buf, 0, len);
			System.out.println(str);
	


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

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

    } // accept loop

} // end of main

}
