目录
1. 读取服务器文件。
创建一个URL对象,然后让URL对象返回输入流,通过该输入流读取URL所包含的资源文件。注意这个程序在本机运行测试时,要开启web服务器,模拟从服务器端读取文件,比如在我的计算机上利用Tomcat做服务器。步骤如下:
a. 启动tomcat服务器:到tomcat主目录下bin目录中运行catalina.bat start
b. 此时,可以读取服务器8080端口下的文件。比如在127.0.0.1:8080端口下有文件index.jsp,在运行的程序中,可以将文件读到运行调试的程序中。
(1) 实验运行结果截图:
(2) 结果描述:
输入网址:http://www.baidu.com,端口:80,程序返回URL中包含的资源文件。在这个程序中,运行结果返回百度首页的资源文件。
(3) 代码补充结果为:
【代码1】 使用字符串name创建url对象:String name = inputURLText.getText().trim();
【代码2】url调用getHost():String hostName = url.getHost();
【代码3】url调用方法返回一个输入流:InputStream in = url .openStream();
(4) 源码:
ReadURLSource.java代码:
public class ReadURLSource {
public static void main(String[] args) {
new NetWin();
}
}
class NetWin extends JFrame implements ActionListener,Runnable{
JButton button;
URL url;
JTextField inputURLText; //输入URL
JTextArea area;
byte b[] = new byte[118];
Thread thread;
NetWin(){
inputURLText = new JTextField(20);
area = new JTextArea(12,12);
button = new JButton("确定");
button.addActionListener(this);
thread = new Thread(this);
JPanel p = new JPanel();
p.add(new JLabel("输入网址:"));
p.add(inputURLText);
p.add(button);
add(area, BorderLayout.CENTER);
add(p,BorderLayout.NORTH);
setBounds(60,60,560,300);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
if(!(thread.isAlive()))
thread = new Thread(this);
try{
thread.start();
}catch (Exception ee){
inputURLText.setText("我正在读取" + url);
}
}
public void run() {
try{
int n = 1;
area.setText(null);
String name = inputURLText.getText().trim();
//【代码1】使用字符串name创建url对象
url = new URL(name);
String hostName = url.getHost();
//【代码2】url调用getHost()
int urlPortNumber = url.getPort();
String fileName = url.getFile();
InputStream in = url .openStream();
//【代码3】 url调用方法返回一个输入流
area.append("\n主机:"+hostName+"端口:"+urlPortNumber+"包含的文件名字:"+fileName);
while((n = in.read(b)) != -1){
String s = new String(b,0,n);
area.append(s);
}
}catch (MalformedURLException e1){
inputURLText.setText(""+e1);
return;
}catch (IOException e1){
inputURLText.setText(""+e1);
return;
}
}
}
2. 会结账的服务器。
客户端和服务器建立套接字连接后,客户将如下格式的账单发送给服务器:
房租:2189元 水费:112.9元 电费:569元 物业费:832元
服务器返回给客户的信息是:
您的账单:
房租:2189元 水费:112.9元 电费:569元 物业费:832元
总额:3702.9元
(1) 实验运行结果截图:
(2) 结果描述:
程序先运行服务器端,显示“正在等待客户”,此时运行客户端,输入服务器的IP和端口号,即客户端和服务器建立套接字连接。服务器端收到客户的地址并打印,客户将指定格式的账单发送给服务器,服务器返回给客户的信息包含了账单以及账单结账后的总额数。
(3) 代码补充结果为:
【代码1】 clientSocket调用getInputStream()返回输入流:
InputStream in = clientSocket.getInputStream();
【代码2】clientSocket调用getOutputStream()返回输出流:
OutputStream out = clientSocket.getOutputStream();
【代码3】创建在端口4331上负责监听的ServerSocket对象:
server = new ServerSocket(4331);
【代码4】server调用accept()返回和客户端相连接的Socket对象:you = server.accept();
(4) 源码:
客户端:ClientItem.java代码:
public class ClientItem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Socket clientSocket = null;
DataInputStream inData = null;
DataOutputStream outData = null;
Thread thread;
Read read = null;
try{
clientSocket = new Socket();
read = new Read();
thread = new Thread(read); //负责读取信息的线程
System.out.print("输入服务器的IP:");
String IP = scanner.nextLine();
System.out.print("输入端口号:");
int port = scanner.nextInt();
String enter = scanner.nextLine(); //消耗回车
if(clientSocket.isConnected()){}
else{
InetAddress address = InetAddress.getByName(IP);
InetSocketAddress socketAddress = new InetSocketAddress(address,port);
clientSocket.connect(socketAddress);
InputStream in = clientSocket.getInputStream();
//【代码1】clientSocket调用getInputStream()返回输入流
OutputStream out = clientSocket.getOutputStream();
//【代码2】clientSocket调用getOutputStream()返回输出流
inData = new DataInputStream(in);
outData = new DataOutputStream(out);
read.setDataInputStream(inData);
read.setDataOutputStream(outData);
thread.start(); //启动负责读信息的线程
}
}catch (Exception e){
System.out.println("服务器已断开" + e);
}
}
}
class Read implements Runnable{
Scanner scanner = new Scanner(System.in);
DataInputStream in;
DataOutputStream out;
public void setDataInputStream(DataInputStream in) {
this.in = in;
}
public void setDataOutputStream(DataOutputStream out) {
this.out = out;
}
@Override
public void run() {
System.out.println("输入账单:");
String content = scanner.nextLine();
try{
out.writeUTF("账单" + content);
String str = in.readUTF();
System.out.println(str);
str = in.readUTF();
System.out.println(str);
str = in.readUTF();
System.out.println(str);
}catch (Exception e){}
}
}
服务器端:ServerItem.java代码:
public class ServerItem {
public static void main(String[] args) {
ServerSocket server = null;
ServerThread thread;
Socket you = null;
while (true){
try{
server = new ServerSocket(4331);
//【代码3】创建在端口4331上负责监听的ServerSocket对象
}catch (IOException e1){
System.out.println("正在监听");
}try{
System.out.println("正在等待客户");
you = server.accept();
//【代码4】server调用accept()返回和客户端相连接的Socket对象
System.out.println("客户的地址:" + you.getInetAddress());
}catch (IOException e){
System.out.println("" + e);
}
if(you != null){
new ServerThread(you).start();
}
}
}
}
class ServerThread extends Thread{
Socket socket;
DataInputStream in = null;
DataOutputStream out = null;
ServerThread(Socket t){
socket = t;
try{
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
}catch (IOException e){}
}
public void run(){
try{
String item = in.readUTF();
Scanner scanner = new Scanner(item);
scanner.useDelimiter("[^0123456789.]+");
if(item.startsWith("账单")){
double sum = 0;
while (scanner.hasNext()){
try{
double price = scanner.nextDouble();
sum = sum + price;
System.out.println(price);
}catch (InputMismatchException exp){
String t = scanner.next();
}
}
out.writeUTF("您的账单:");
out.writeUTF(item);
out.writeUTF("总额:" + sum + "元");
}
}catch (Exception exp){}
}
}
3. 读取服务器端的窗口。
客户端利用套接字连接将服务器端的JFrame对象读取到客户端。首先将服务器端的程序编译通过,并运行起来,等待请求套接字连接。
(1) 实验运行结果截图:
(2) 结果描述:
程序先运行服务器端,显示“正在等待客户”,服务器端等待请求套接字连接运行客户端,输入服务器的IP和端口号,此时客户端利用套接字连接将服务器端的JFrame对象读取到客户端,显示服务器端的窗口。
(3) 代码补充结果为:
【代码1】mysocket调用getInputStream()返回输入流:
InputStream in = mysocket.getInputStream();
【代码2】mysocket调用getOutputStream()返回输出流:
OutputStream out = mysocket.getOutputStream();
【代码3】创建在端口4331上负责监听的ServerSocket对象:
server = new ServerSocket(4331);
【代码4】server调用accept()返回和客户端相连接的Socket对象:you = server.accept();
(4) 源码:
Client.java代码:
public class Client {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Socket mysocket = null;
ObjectInputStream inObject = null;
ObjectOutputStream outObject = null;
Thread thread;
ReadWindow readWindow = null;
try{
mysocket = new Socket();
readWindow = new ReadWindow();
thread = new Thread(readWindow);
System.out.print("输入服务器的IP:");
String IP = scanner.nextLine();
System.out.print("输入端口号:");
int port = scanner.nextInt();
if(mysocket.isConnected()){}
else{
InetAddress address = InetAddress.getByName(IP);
InetSocketAddress socketAddress = new InetSocketAddress(address,port);
mysocket.connect(socketAddress);
InputStream in = mysocket.getInputStream();
//【代码1】mysocket调用getInputStream()返回输入流
OutputStream out = mysocket.getOutputStream();
//【代码2】mysocket调用getOutputStream()返回输出流
inObject = new ObjectInputStream(in);
outObject = new ObjectOutputStream(out);
readWindow.setObjectInputStream(inObject);
thread.start(); //启动负责读信息的线程
}
}
catch (Exception e){
System.out.println("服务器已断开" + e);
}
}
}
class ReadWindow implements Runnable{
ObjectInputStream in;
public void setObjectInputStream(ObjectInputStream in) {
this.in = in;
}
@Override
public void run() {
double result = 0;
while (true){
try {
javax.swing.JFrame window = (javax.swing.JFrame)in.readObject();
window.setTitle("这是从服务器上读入的窗口");
window.setVisible(true);
window.requestFocusInWindow(); //requestFocus();
window.setSize(600,800);
}catch (Exception e){
System.out.println("与服务器已断开" + e);
break;
}
}
}
}
Server.java代码:
public class Server {
public static void main(String[] args) {
ServerSocket server = null;
ServerThread thread;
Socket you = null;
while (true){
try{
server = new ServerSocket(4331);
//【代码3】创建在端口4331上负责监听的ServerSocket对象
}catch (IOException e1){
System.out.println("正在监听");
}
try{
System.out.println("正在等待客户");
you = server.accept();
//【代码4】server调用accept()返回和客户端相连接的Socket对象
System.out.println("客户的地址:" + you.getInetAddress());
}catch (IOException e){
System.out.println("" + e);
}
if(you != null){
new ServerThread(you).start();
}else {
continue;
}
}
}
}
class ServerThread extends Thread{
Socket socket;
ObjectInputStream in = null;
ObjectOutputStream out = null;
JFrame window;
JTextArea text;
ServerThread(Socket t){
socket = t;
try{
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
}catch (IOException e){}
window = new JFrame();
text = new JTextArea();
for(int i=1;i<=20;i++){
text.append("你好,我是服务器上的文本区组件\n");
}
text.setBackground(Color.yellow);
window.add(text);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void run(){
try{
out.writeObject(window);
}catch (Exception e){
System.out.println("客户离开");
}
}
}