현재 소켓 프로그래밍을 배우고 있으며 도움이 필요한 문제가 발생했습니다. 내가하려고하는 것은 웹 호스트에 연결하고 기본 페이지를 다운로드 한 다음 호스트와의 연결을 끊는 Java 클래스를 작성하는 것입니다. 이 작업을하기 위해 URLConnection을 사용하는 것이 더 간단하다는 것을 알고 있지만 소켓 클래스를 배우려고합니다. 웹 서버에 성공적으로 연결했지만 페이지를 가져 오는 데 어려움이 있습니다. 이것은 내가 지금까지 작업 (그리고 작동하지) 않은 것입니다 :소켓이있는 웹 페이지 얻기
import java.io.*;
import java.net.*;
import java.lang.IllegalArgumentException;
public class SocketsFun{
public static void main(String[] myArgs){
// Set some variables
String theServer = null;
String theLine = null;
int thePort = 0;
Socket theSocket = null;
boolean exit = false;
boolean socketCheck = false;
BufferedReader theInput = null;
// Grab the server and port number
try{
theServer = myArgs[0];
thePort = Integer.parseInt(myArgs[1]);
System.out.println("Opening a connection to " + theServer + " on port " + thePort);
} catch(ArrayIndexOutOfBoundsException aioobe){
System.out.println("usage: SocketsFun host port");
exit = true;
} catch(NumberFormatException nfe) {
System.out.println("usage: SocketsFun host port");
exit = true;
}
if(!exit){
// Open the socket
try{
theSocket = new Socket(theServer, thePort);
} catch(UnknownHostException uhe){
System.out.println("* " + theServer + " does not exist");
} catch(IOException ioe){
System.out.println("* " + "Connection Refused");
} catch(IllegalArgumentException iae){
System.out.println("* " + thePort + " Not A Valid TCP/UDP Port.");
}
// Print out some stuff
try{
System.out.println("Connected Socket: " + theSocket.toString());
} catch(Exception e){
System.out.println("* " + "No Open Socket");
}
try{
theInput = new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
while ((theLine = theInput.readLine()) != null){
System.out.println(theLine);
}
theInput.close();
} catch(IOException ioe){
System.out.println("* " + "No Data To Read");
} catch(NullPointerException npe){
System.out.println("* " + "No Data To Read");
}
// Close the socket
try{
socketCheck = theSocket.isConnected();
} catch(NullPointerException npe){
System.out.println("* " + "No Socket To Close");
}
}
}
}
내가 걸려 모든 "컬" "살쾡이 - 덤프"에서 출력, 또는 "wget을 될 일을 뱉어이 클래스이다 "등 모든 도움을 주시면 대단히 감사하겠습니다.
제쳐두고, 당신이하고있는 일에 대해 정말로 확신하지 않는 한'NullPointerException'을 잡아 내지 않기를 강력히 권장합니다. 'NullPointerException'은 대개 중대한 버그를 나타내며 스택 트레이스가있는 barf 프로그램을 사용하는 것이 일반적으로 매우 유용합니다. –