Avatar of ocean O
ocean OFlag for United States of America

asked on 

TCP socket

Hi, I am new to TCP socket. I have a question about socket. I need modify the TCP Client program below, to fetch the webpage at: www.cs.montclair.edu/~wangd/pubs.html. I run the code below, but got an 404 error.

Any inputs are appreciated.

Below is the code.


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

class TCPClient {  
   public static void main(String argv[]) throws Exception
   {    
         String sentence;  
       String modifiedSentence;
     
      BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));  
       
        Socket clientSocket = new Socket("cs.montclair.edu", 80);

      DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());  
      BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));    

     System.out.println("Type in any sentence: ");    
     sentence = inFromUser.readLine();    
    System.out.println(" in sentence: "+sentence);
     outToServer.writeBytes("GET/~wangd/pubs.html" + '\n');  
    outToServer.flush();
    modifiedSentence = inFromServer.readLine();  
    System.out.println("FROM SERVER: " + modifiedSentence);    
    clientSocket.close();    
    }
}

* WebSocketsTCP/IPJava

Avatar of undefined
Last Comment
CEHJ
Avatar of Gerwin Jansen
Gerwin Jansen
Flag of Netherlands image

I'm not that familiar with Java but your URL would need a space after the GET:

outToServer.writeBytes("GET /~wangd/pubs.html" + '\n');  
Avatar of ocean O
ocean O
Flag of United States of America image

ASKER

Hi Gerwin:
Thanks for the comments, I tried with the space after the GET, but I still get an error:
Exception in thread "main" java.net.SocketTimeoutException: Read timed out
Avatar of dpearson
dpearson

A socket is a very low level way to communicate.  You are looking to send an "HTTP Request".  Currently you are sending the actual text string "GET /~wangd/pubs.html".  But that's not an HTTP Request (which has a whole complex format for how the data is prepared and sent).

You almost certainly don't want to do this using a raw TCP Socket.

Instead you should use a library - which will itself using a TCP socket to do the work.
Have a look at the HTTPClient library, with an example shown here:
https://openjdk.java.net/groups/net/httpclient/recipes.html

The "URI" passed in would be a normal url, like you'd see in the top of a browser, like
"http://cs.montclair.edu/~wangd/pubs.html"
and the first example on that page shows how to execute a "GET" request.

Avatar of David Favor
David Favor
Flag of United States of America image

As @dperason mentioned.

TCP != HTTP

If you're trying to access HTTP/HTTPS you'll likely use wget, curl, httrack or maybe a libcurl binding for Java.

Or you'll have to rewrite one of these tools from scratch... which is not recommended, as this would take a significant amount of time.

Another options is to use a very lightweight program like netcat, if curl or wget are to heavy.
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You almost certainly don't want to do this using a raw TCP Socket.
Quite right. Unless of course  this is a HTTP learning exercise. If that's the case, you're doing things back to front. First you need to know the protocol before coding. As someone pointed out, it's clear that you don't yet know it, so you need to learn it first.
SOLUTION
Avatar of krakatoa
krakatoa
Flag of United Kingdom of Great Britain and Northern Ireland image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of ocean O
ocean O
Flag of United States of America image

ASKER

Hi Krakatoa:
Thank you for the code, but I got an error when I try to compile the code:
TCPClients.java:3: error: package java.net.http does not exist
import java.net.http.*;
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Have you got an old version of the JDK? That need at least Java 11
Avatar of dpearson
dpearson

Also it's important to recognize that Krakatoa's implementation still includes the original code opening a TCP socket to the server.

This however is not doing anything and should be removed.

The HttpClient library is opening another socket internally and doing the work...as I suggested at the top of the question here :)

Doug
Avatar of krakatoa
krakatoa
Flag of United Kingdom of Great Britain and Northern Ireland image

Well the server will give a response over that socket, which is the written to the stdout. But it stayed in just pro forma.
Avatar of dpearson
dpearson

The server will respond - but there's basically two completely unrelated communications happening here, that are both occurring in the same function.

It's like as if I called up one friend on my home phone and another friend on my cell phone and then wrote down what I was hearing from my two friends.  It's two unrelated conversations.  And to further complete the analogy I would put one of the phones on "mute" - so my friend couldn't hear me :)  The TCP socket here will not get a valid response since we're not sending a valid request.

It might be simpler to just focus on one of these conversations (the HTTPClient one) which is actually going to work.  The other one (the TCP socket) will not produce a successful response (since it's not sending a valid HTTP request).  That code can be deleted from this example and what remains is all that is needed.
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of dpearson
dpearson

Exactly CEHJ :)

And we end up with something very akin to the first sample here:
https://openjdk.java.net/groups/net/httpclient/recipes.html

Doug

Avatar of krakatoa
krakatoa
Flag of United Kingdom of Great Britain and Northern Ireland image

Doug, as I said, I left that connection in just to show a return from the server, as the other channel was explicitly for the request. Also, it should be evident to the OP from the fact that there was no counterpart in the other direction, that it had been left in to highlight the point. ;)
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

:) But don't forget that was krakatoa's code
Java
Java

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

102K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo