user2875985
user2875985

Reputation: 11

TCP connection capable of sending http requests

I am trying to build a simple web server (TCP) capable of receiving, treating and responding http requests. I have already stablished a TCP connection between Client and Server, problem is, although I've tried, I haven't managed to do the http request. These are the Client and Server codes in Java:

CLIENT CLASS:

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.Socket;

import java.net.UnknownHostException;

public class SocketCliente {

private String hostname;
private int porta;
Socket socketCliente;

public SocketCliente(String hostname, int porta){
    this.hostname = hostname;
    this.porta = porta;
}

public void connect() throws UnknownHostException, IOException{
    System.out.println("Tentando se conectar com "+hostname+":"+porta);
    socketCliente = new Socket(hostname,porta);
    System.out.println("A conexão foi realizada");
}

public void readResponse() throws IOException{
    String userInput;
    BufferedReader stdIn = new BufferedReader(new InputStreamReader(socketCliente.getInputStream()));

    System.out.println("Responsta do servidor:");
    while ((userInput = stdIn.readLine()) != null) {
        System.out.println(userInput);
    }
}

public static void main(String arg[]){
    //Creating a SocketClient object
    SocketCliente client = new SocketCliente ("localhost",30000);
    try {
        //trying to establish connection to the server
        client.connect();
        //if successful, read response from server
        client.readResponse();

    } catch (UnknownHostException e) {
        System.err.println("A conexão não pode ser estabelecida.");
    } catch (IOException e) {
        System.err.println("Conexão não estabelecida, pois o servidor pode ter problemas."+e.getMessage());
    }
}
}

SERVER CLASS

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;


public class SocketServidor {

private ServerSocket serverSocket;
private int porta;

public SocketServidor(int porta) {
    this.porta = porta;
}

public void start() throws IOException {
    System.out.println("Começando o servidor na porta:" + porta);
    serverSocket = new ServerSocket(porta);

    //Listen for clients. Block till one connects

    System.out.println("Esperando o cliente");
    Socket client = serverSocket.accept();

    //A client has connected to this server. Send welcome message
    sendMensagemDeBoasVindas(client);
}

private void sendMensagemDeBoasVindas(Socket cliente) throws IOException {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(cliente.getOutputStream()));
    writer.write("A sua conexão com o SocketServidor foi feita");
    writer.flush();
}

/**
* Creates a SocketServer object and starts the server.
*
* @param 
*/
public static void main(String[] args) {
    // Setting a default port number.
    int portNumber = 30000;

    try {
        // initializing the Socket Server
        SocketServidor socketServer = new SocketServidor(portNumber);
        socketServer.start();

        } catch (IOException e) {
        e.printStackTrace();
    }
}
}

I truly have no idea of how I can make a http request. I've tried creating a http class, I've tried sending the request from the existing Client class, but nothing has worked so far. And all the google searches haven't helped.

A friend, who's also trying to do it, told me that you need to send the request from the Client class to the Server class after they've already made the connection. How do I do this?

Please, can you help me?

@Robin-Green CLIENT CLASS:

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SocketCliente {
private String hostname;
private int porta;
Socket socketCliente;

public SocketCliente(String hostname, int porta){
    this.hostname = hostname;
    this.porta = porta;
}

public void connect() throws UnknownHostException, IOException{
    System.out.println("Tentando se conectar com "+hostname+":"+porta);
    socketCliente = new Socket(hostname,porta);
    System.out.println("A conexão foi realizada");
}

public void readResponse() throws IOException{
    String userInput;
    BufferedReader stdIn = new BufferedReader(new InputStreamReader(socketCliente.getInputStream()));

    System.out.println("Responsta do servidor:");
    while ((userInput = stdIn.readLine()) != null) {
        System.out.println(userInput);
    }
}
public void HTTPCliente() throws Exception{
    PrintWriter out = new PrintWriter(new OutputStreamWriter(socketCliente.getOutputStream()));
    System.out.println("GET / HTTP/1.1");
    System.out.println("User-Agent: test/1.0");
    System.out.println("Host: localhost");
    System.out.println("Accept: */*");
}

public static void main(String arg[]){
    //Creating a SocketClient object
    SocketCliente client = new SocketCliente ("localhost",30000);
    try {
        //trying to establish connection to the server
        client.connect();
        //if successful, read response from server
        client.readResponse();
        try {
            //se http obtiver sucesso
            client.HTTPCliente();
        } catch (Exception ex) {
            Logger.getLogger(SocketCliente.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (UnknownHostException e) {
        System.err.println("A conexão não pode ser estabelecida.");
    } catch (IOException e) {
        System.err.println("Conexão não pode ser feita por problemas no servidor."+e.getMessage());
    }
}

}

Upvotes: 0

Views: 2647

Answers (1)

Robin Green
Robin Green

Reputation: 33033

You need to send something like this:

GET / HTTP/1.1
User-Agent: test/1.0
Host: localhost
Accept: */*

so maybe:

PrintWriter out = new PrintWriter(new OutputStreamWriter(socketCliente.getOutputStream()));
out.println("GET / HTTP/1.1");
out.println("User-Agent: test/1.0");
out.println("Host: localhost");
out.println("Accept: */*");

but by the way, this is the low-level, more complicated way. It's easier to do it with a high-level API. But maybe that is not allowed in this homework assignment, I don't know.

Upvotes: 1

Related Questions