我正在尝试从服务器向客户端发送文件信息,但无法在客户端接收信息。我认为这是一个错误的流,但无法找到它。
我调试了代码,我发现信息读取得很好但是当遇到问题时会发生一些不好的事情:
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();
}
}
}
答案 0 :(得分:3)
客户端正在等待一行(即由返回/换行符终止),而服务器没有发送此行。您可以在服务器中自行添加换行符:
while ((readLine = read.readLine()) != null) {
write.write(readLine+"\n");
write.flush();
}