Question:

How do I find and print one line from a socket in Java?

by  |  earlier

0 LIKES UnLike

I think I want the program to check every line of the socket that is being read and if it contains a certain phrase or line it will print it. I want it to find a variable number within that line and print ONLY that number. How would I do that?

This is my template for the program:

http://www.iro.umontreal.ca/~vaucher/Java/Sockets/WWW/GetHttp.java

 Tags:

   Report

1 ANSWERS


  1. If, for example, you wanted to extract the number of articles in the English Wikipedia, as seen on

    http://en.wikipedia.org/wiki/Main_Page , you could use Java's Pattern and Matcher classes. Add the line

    import java.util.regex.*;

    to the other imports of the program, and after the line socket.close();

    Pattern pattern = Pattern.compile("([0-9],[0-9]{3}" + ",[0-9]{3})");

        Matcher m = pattern.matcher(text);

        m.find();

         String group = m.group(1);

    System.out.println(group);

    The page the program receives from Wikipedia contains a number like "2,497,349". To find this number, the pattern looks for seven digit number with commas. If there were more such numbers on the page, we could find them too by calling m.find() again, or if we wanted a specific of these numbers, add some context to the Pattern, outside of the round brackets.

    By the way, I hat do change one line of the template to get it working:

          to_server.print("GET " + filename + " HTTP/1.1\r\nHost: " + host + "\r\n\r\n");

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.