4
我想從服務器發送文件信息到客戶端,但無法接收客戶端的信息。我認爲這是一個錯誤的流,但無法找到它。客戶端無法從服務器接收信息
我調試代碼,我看到,當涉及到線上的信息是讀好,但隨後壞事happend:
while ((readLine = read.readLine()) != null) {
這是null
,一切都結束。
public class Server {
private String urlFile = "http://riemann.fmi.uni-ofia.bg/vladov/students/boil.txt";
private ServerSocket serverSocket = null;
private BufferedReader read = null;
private BufferedWriter write = null;
private FileReader fileReader = null;
URLConnection urlConnection = null;
void acceptConnection() {
try {
serverSocket = new ServerSocket(3000);
Socket client = null;
while (true) {
client = serverSocket.accept();
handleConnection(client);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void handleConnection(Socket clientSocket) {
try {
URL url = new URL(urlFile);
urlConnection = url.openConnection();
read = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
write = new BufferedWriter(new OutputStreamWriter(
clientSocket.getOutputStream()));
String readLine = null;
while ((readLine = read.readLine()) != null) {
write.write(readLine);
write.flush();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void tearDownConnection() {
try {
write.close();
read.close();
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客戶:
public class Client {
Socket client = null;
BufferedReader reader = null;
BufferedWriter writer = null;
void connectToServer(String hostAddress, int port) {
try {
System.out.println("Client is waitting.");
client = new Socket(hostAddress, port);
reader = new BufferedReader(new InputStreamReader(
client.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(
client.getOutputStream()));
String readedLine = null;
readedLine = reader.toString();
while ((readedLine = reader.readLine()) != null) {
System.out.println(readedLine);
}
} catch (UnknownHostException e) {
System.out.println("Host name is unkown.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
void tearDownConnection() {
try {
if (client != null) {
client.close();
}
if (writer != null) {
writer.close();
}
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
http://riemann.fmi.uni-ofia.bg/vladov/students/boil.txt上是否有任何內容? –
是的。當我調試時,我發現有東西在讀。你必須在http://之前輸入 – Xelian
嘿,不是正確的地址:http://riemann.fmi.uni-sofia.bg/vladov/students/boil.txt?我認爲你正在閱讀的數據只是HTTP 404響應。 – user35443