我想要做一個客戶端的簡單示例,該客戶端使用8080端口連接到任何網站並從服務器打印第一個輸入。但我甚至無法連接到服務器。 用Wireshark運行TCP的頭文件,我意識到服務器沒有回答。 我已經關閉防火牆,防病毒,並在我的路由器中設置轉發端口,但我仍然無法連接到服務器。Java - 套接字編程/阻塞端口
這裏是我的代碼:
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
'stackoverflow.com'沒有監聽端口8080 –
HTTP端口是80端口。8080是替代HTTP端口 – Dampsquid
好吧,現在它的工作原理是stackoverflow.com,但是當我嘗試其他網站時,它會拋出一個讀超時異常。會是什麼呢? –