【问题标题】:TCP connection capable of sending http requests能够发送http请求的TCP连接
【发布时间】:2013-10-13 21:54:05
【问题描述】:

我正在尝试构建一个能够接收、处理和响应 http 请求的简单 Web 服务器 (TCP)。我已经在客户端和服务器之间建立了一个 TCP 连接,问题是,虽然我已经尝试过了,但我还没有设法完成 http 请求。 这些是 Java 中的客户端和服务器代码:

客户类别:

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());
    }
}
}

服务器类

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();
    }
}
}

我真的不知道如何发出 http 请求。我已经尝试创建一个 http 类,我已经尝试从现有的 Client 类发送请求,但到目前为止没有任何效果。而且所有的谷歌搜索都没有帮助。

一位也在尝试这样做的朋友告诉我,您需要在他们已经建立连接后将请求从 Client 类发送到 Server 类。我该怎么做?

拜托,你能帮帮我吗?

@罗宾-格林 客户类别:

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());
    }
}

}

【问题讨论】:

  • 请向我们展示您尝试从客户端发送请求的代码。
  • 对不起,我现在没有它:很遗憾,我把它忘在学校实验室的电脑上了。

标签: java http tcp


【解决方案1】:

您需要发送如下内容:

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

也许:

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: */*");

但顺便说一下,这是低级的、更复杂的方法。使用高级 API 更容易做到这一点。但也许这在这个家庭作业中是不允许的,我不知道。

【讨论】:

  • 好的。我在我的客户课上试过这个,但是什么也没发生:它没有打印或给出错误。那么,服务器在这个过程中做了什么?我如何让他得到这个请求? P.S.:谢谢你的回答!
  • HTTP 是一种允许请求以特定资源为目标的协议。由于您只有一个资源,您可以忽略请求中的数据,但这是一种作弊。所以你真的应该解析请求的第一行,从中提取 URL(在这种情况下是 /),如果它是你所期望的,则产生一个适当的 HTTP 响应。至于为什么什么也没发生,我不知道 - 请发布您的更新代码。
  • 抱歉耽搁了。我已经更新了代码。再次感谢您的帮助。
  • 抱歉,不够详细。回到电脑前请贴出实际代码。
  • 我现在随身携带的代码还是我留在学校的代码?因为我在学校的那个我只能在星期三才能拿到......
猜你喜欢
  • 2013-01-03
  • 2016-02-02
  • 2015-10-27
  • 2017-04-26
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 2012-05-03
  • 2011-07-24
相关资源
最近更新 更多