下面的程序为URL类的应用,请填空把程序补充完整。 import java.net.*; import java.io.*; public class URLTest { public static void main(String[] args) { URL url = null; InputStream is; try { url = new URL("http://www.xhu.edu.cn");
时间: 2024-04-26 08:25:38 浏览: 137
is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
相关问题
3.下面的程序为URL类的应用,请填空把程序补充完整。 import java.net.*; import java.io.*; public class URLTest { public static void main(String[] args) { URL url = null; InputStream is; try { url = new URL("http://www.xhu.edu.cn");
is = url.openStream(); // 打开URL连接并获取输入流
BufferedReader br = new BufferedReader(new InputStreamReader(is)); // 将字节流转换为字符流
String line; // 存储读取到的每一行数据
while ((line = br.readLine()) != null) { // 循环读取每一行数据
System.out.println(line); // 输出每一行数据
}
br.close(); // 关闭流
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
下面的程序为利用Socket实现客户端和服务端通信,请填空把程序补充完整。 //服务器端(ServerTest.java文件清单:) import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; class Server
Test{
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端已连接,客户端信息如下:" + socket);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
while (true) {
String message = reader.readLine();
if (message == null) {
break;
}
System.out.println("客户端发送的消息是:" + message);
writer.println("已收到消息:" + message);
}
reader.close();
writer.close();
socket.close();
serverSocket.close();
}
}
// 客户端(ClientTest.java文件清单:)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
class ClientTest {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost", 8888);
System.out.println("已连接服务器,服务器信息如下:" + socket);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String message = console.readLine();
writer.println(message);
String response = reader.readLine();
System.out.println("收到服务器的回复:" + response);
}
}
}
阅读全文