Solved

java read vs readline

Posted on 2009-07-13
2
308 Views
Last Modified: 2013-11-23
First let me admit that I barely know java enough to be dangerous.  

I'd like to modify the code below (in the function run) so that when it receives a message, it prints it to the console, but I don't want it to print a CR LF.

I get some compiler warnings about depreciated functions, so fee free to update the code where it makes sense to do so:

An added bonus would be to make the program exit gracefully if the user hits ctrl-c
import java.io.*;

import java.net.*;

import java.security.*;
 

/**

 * Title:        Sample Server

 * Description:  This utility will accept input from a socket, posting back to the socket before closing the link.

 * It is intended as a template for coders to base servers on. Please report bugs to brad at kieser.net

 * Copyright:    Copyright (c) 2002

 * Company:      Kieser.net

 * @author B. Kieser

 * @version 1.0

 */
 

public class sample_server {
 

  private static int port=12310, maxConnections=0;

  // Listen for incoming connections and handle them

  public static void main(String[] args) {

    int i=0;
 

    try{

      ServerSocket listener = new ServerSocket(port);

      Socket server;
 

      while((i++ < maxConnections) || (maxConnections == 0)){

        doComms connection;
 

        server = listener.accept();

        doComms conn_c= new doComms(server);

        Thread t = new Thread(conn_c);

        t.start();

      }

    } catch (IOException ioe) {

      System.out.println("IOException on socket listen: " + ioe);

      ioe.printStackTrace();

    }

  }
 

}
 

class doComms implements Runnable {

    private Socket server;

    private String line,input;
 

    doComms(Socket server) {

      this.server=server;

    }
 

    public void run () {
 

      input="";
 

      try {

        // Get input from the client

        DataInputStream in = new DataInputStream (server.getInputStream());

        PrintStream out = new PrintStream(server.getOutputStream());
 

        while((line = in.readLine()) != null) {

          input=input + line;

        }
 

        // Now write to the client
 

        System.out.print("> " + input);
 

        server.close();

      } catch (IOException ioe) {

        System.out.println("IOException on socket listen: " + ioe);

        ioe.printStackTrace();

      }

    }

}

Open in new window

0
Comment
Question by:MrGone06095
2 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 250 total points
ID: 24844590
Try the following:
import java.io.*;

import java.net.*;

import java.security.*;

 

/**

 * Title:        Sample Server

 * Description:  This utility will accept input from a socket, posting back to the socket before closing the link.

 * It is intended as a template for coders to base servers on. Please report bugs to brad at kieser.net

 * Copyright:    Copyright (c) 2002

 * Company:      Kieser.net

 * @author B. Kieser

 * @version 1.0

 */

 

public class sample_server {

 

  private static int port=12310, maxConnections=0;

  // Listen for incoming connections and handle them

  public static void main(String[] args) {

    int i=0;

 

    try{

      ServerSocket listener = new ServerSocket(port);

      Socket server;

 

      while((i++ < maxConnections) || (maxConnections == 0)){

        doComms connection;

 

        server = listener.accept();

        doComms conn_c= new doComms(server);

        Thread t = new Thread(conn_c);

        t.start();

      }

    } catch (IOException ioe) {

      System.out.println("IOException on socket listen: " + ioe);

      ioe.printStackTrace();

    }

  }

 

}

 

class doComms implements Runnable {

    private Socket server;

    private String line,input;

 

    doComms(Socket server) {

      this.server=server;

    }

 

    public void run () {

 

      input="";

 

      try {

        // Get input from the client

        BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));

        PrintWriter out = new PrintWriter(server.getOutputStream(), true);

 

        while((line = in.readLine()) != null) {

          input=input + line;

        }

 

        // Now write to the client

 

        out.println("> " + input);

 

        server.close();

      } catch (IOException ioe) {

        System.out.println("IOException on socket listen: " + ioe);

        ioe.printStackTrace();

      }

    }

}

Open in new window

0
 
LVL 92

Assisted Solution

by:objects
objects earned 250 total points
ID: 24844982
> An added bonus would be to make the program exit gracefully if the user hits ctrl-c

try using a shutdown hook

http://helpdesk.objects.com.au/java/how-can-i-get-some-code-run-when-my-application-shuts-down
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now