1

我正在尝试做一个简单的客户端示例,该客户端使用 8080 端口连接到任何网站并打印来自服务器的第一个输入。但我什至无法连接到服务器。用 Wireshark 跟踪 TCP 的标头,我意识到服务器没有响应。我已经关闭了防火墙、防病毒软件并在路由器中设置了转发端口,但仍然无法连接到服务器。

这是我的代码:

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;


public class ProtocoloX {
    //private byte[] bytes = new byte[1024];
    private byte[] bytes = new byte[]{(byte) 0xC6, 0x57, 0x54, (byte) 0x95, 0x5E, (byte) 0x9E, 0x6B, (byte) 0xC6, 0x55, 0x17, 0x55,0x52, (byte) 0x9E, 0x21};
    private Socket cliente;
    private final String HOST = "stackoverflow.com";
    private final int PORT = 8080;

    public boolean connect(){
        this.cliente = new Socket();
        System.out.println("-- Trying to connect: "+HOST+":"+PORT);
        InetSocketAddress socketAddress = new InetSocketAddress(HOST, PORT); 
        try {
            this.cliente.connect(socketAddress, 10000000);
        } catch (IOException e) {
            System.out.println(e);
            System.out.println("-- CONNECTION PROBLEM ");
            return false;
        }
        System.out.println("-- Connection successful");
        return true;
    }

    private void receive(){
        InputStream stream = null;  
        System.out.println("-- Reading data...");
        try {
            stream = this.cliente.getInputStream();
            try {
                int count = stream.read(this.bytes);
                System.out.println("count:"+count);
                System.out.println("bytes:"+this.bytes);
            } catch (IOException e) {
                System.out.println("-- DATA READING PROBLEM");
                e.printStackTrace();
            }
        } catch (IOException e) {
            System.out.println("-- DATA READING PROBLEM");
            e.printStackTrace();
        }
        System.out.println("-- Data read successful");
    }


    public static void main(String[] args) throws UnknownHostException, IOException {
        ProtocoloX protocolo = new ProtocoloX();
        if(protocolo.connect()){
            protocolo.receive();
        }

    }
}

什么可能导致问题?感谢:D

4

2 回答 2

0

You won't get anything on port 8080 instead try on '80'. 80 is the default http port where internet websites listen for requests.

于 2013-09-26T14:35:11.627 回答
0

Many WAN websites will not respond to an explicitly specified port query. For example, visiting http://www.stackoverflow.com:8080 in a web broswer will not get a response either. Verify that the server you are connecting to will accept connections on the 8080 port.

于 2013-09-26T14:35:19.930 回答