一、实验目的
- 本次实验的主要目的是练习网络通信程序的设计方法,并掌握计算机网络基
- 础知识、Java语言网络通信程序类库的结构和使用方法。
二、实验要求
- 1. 认真阅读实验内容,完成实验内容所设的题目。
- 2. 能够应用多种编辑环境编写Java语言源程序。
- 3. 认真体会计算机网络和Java语言网络通信程序的概念。
- 4. 将实验结果书写在实验报告中。
三、实验内容
运行下列程序,观察程序的运行结果
A.程序一
package org.example; import java.io.*; import java.util.Scanner; import java.net.InetAddress; import java.net.UnknownHostException; public class Main { public static void main(String[] args) throws Exception { InetAddress inet = InetAddress.getByName("www.baidu.com"); System.out.println(inet); System.out.println(inet.getHostName()); System.out.println(inet.getHostAddress()); InetAddress inet1 = InetAddress.getLocalHost(); System.out.println(inet1); System.out.println(inet1.getHostName()); System.out.println(inet1.getHostAddress()); } }
运行结果如下
B.程序二
服务器端(Main)
package org.example;// 服务器端 import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class Main { public static void main(String[] args) { ServerSocket ss = null; Socket s = null; InputStream is = null; OutputStream os = null; try { ss = new ServerSocket(9090); s = ss.accept(); is = s.getInputStream(); byte[] b = new byte[20]; int len; while ((len = is.read(b)) != -1) { String str = new String(b, 0, len); System.out.print(str); } System.out.println("收到来自于" + s.getInetAddress().getHostAddress() + "的连接"); os = s.getOutputStream(); os.write("我已收到你的信息".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (s != null) { try { s.close(); } catch (IOException e) { e.printStackTrace(); } } if (ss != null) { try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
运行完服务器端后再运行客户端返回看即可出现127.0.0.1
客户端(Client)
package org.example; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; public class Client { public static void main(String[] args) { Socket socket = null; OutputStream os = null; InputStream is = null; try { socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090); os = socket.getOutputStream(); os.write("我是客户端,请多关照".getBytes()); socket.shutdownOutput(); is = socket.getInputStream(); byte[] b = new byte[20]; int len; while ((len = is.read(b)) != -1) { String str = new String(b, 0, len); System.out.print(str); } } catch (IOException e) { e.printStackTrace(); } finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
先运行Main然后再运行Client
运行结果如下
C.程序三
接收端(UDPserver)
package org.example; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; public class UDOserver { public static void main(String[] args) { DatagramSocket ds = null; try { ds = new DatagramSocket(9090); byte[] b = new byte[1024]; DatagramPacket pack = new DatagramPacket(b, 0, b.length); ds.receive(pack); String str = new String(pack.getData(), 0, pack.getLength()); System.out.println(str); } catch (IOException e) { e.printStackTrace(); } finally { if (ds != null) { ds.close(); } } } }
发送端(UDPclient)
package org.example;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UDPclient {
public static void main(String[] args) {
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
byte[] b = "你好,我是要发送的数据".getBytes();
DatagramPacket pack = new DatagramPacket(b, 0, b.length, InetAddress.getByName("127.0.0.1"), 9090);
ds.send(pack);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
}
}
D.程序四
package org.example;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class Fyt {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.hhdu.edu.cn/85/c9/c23a34249/page.htm");
System.out.println(url.getProtocol());
System.out.println(url.getHost());
System.out.println(url.getPort());
System.out.println(url.getFile());
System.out.println(url.getRef());
System.out.println(url.getQuery());
InputStream is = url.openStream();
byte[] b = new byte[20];
int len;
len = is.read(b);
String str = new String(b, 0, len);
System.out.print(str);
is.close();
URLConnection urlConn = url.openConnection();
InputStream is1 = urlConn.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("E:\\桌面文件\\javatxt文档\\a.txt"));
byte[] b1 = new byte[20];
int len1;
while ((len1 = is1.read(b1)) != -1) {
fos.write(b1, 0, len1);
}
fos.close();
is1.close();
}
}
- 1.这个代码类似于抓包了,大概意思是从指定的URL上下载文件并将其内容保存到本地文件中。使用URL类创建一个指向特定URL的对象,然后通过对该URL对象调用方法来获取URL的各种属性,如协议、主机名、端口、文件名、引用和查询部分。
- 2.接着,打开URL的输入流,从URL地址对应的资源中读取内容。在这里,首先创建一个字节数组b用于存放读取到的数据,使用输入流is的read(b)方法读取数据,然后将字节数组转换成字符串并打印输出。
- 3.随后,通过url.openConnection()方法创建一个URLConnection对象,并从中获取输入流is1。然后创建一个FileOutputStream对象fos,将从输入流is1读取的数据写入到本地文件"E:\\桌面文件\\javatxt文档\\a.txt"中。
- 4.最后,关闭所有打开的流,释放相关的资源。
- 这段代码的作用是连接到指定URL,抓取该URL对应的资源,然后将其内容保存为本地文件。
本地文件如下图所示
四、编写程序完成下列功能
(1)编写一个服务器端的程序Server.java,该程序在8000端口监听客户端的
请求,如果与客户端连接后,收到客户端发送的数据不是字符串“bye”,则在服
务器端打印客户端发来的数据,并向客户端回送一条从键盘输入的信息,若客户
端发来的数据是字符串“bye”,则关闭服务器端程序。
package org.example;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8000);
System.out.println("服务器已启动,等待客户端连接...");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("客户端已连接");
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
Scanner scanner = new Scanner(System.in);
String clientMessage;
while ((clientMessage = reader.readLine()) != null) {
System.out.println("客户端消息:" + clientMessage);
if (clientMessage.equals("bye")) {
System.out.println("客户端已断开连接");
break;
} else {
System.out.print("请输入要发送给客户端的信息:");
String serverResponse = scanner.nextLine();
writer.write(serverResponse);
writer.newLine();
writer.flush();
}
}
reader.close();
writer.close();
clientSocket.close();
if (clientMessage.equals("bye")) {
System.out.println("关闭服务器端程序");
break;
}
}
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端
package org.example;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8000);
System.out.println("已连接到服务器端");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("请输入要发送给服务器端的信息:");
String clientMessage = scanner.nextLine();
writer.write(clientMessage);
writer.newLine();
writer.flush();
if (clientMessage.equals("bye")) {
System.out.println("断开与服务器端的连接");
break;
}
String serverResponse = reader.readLine();
System.out.println("服务器端消息:" + serverResponse);
if (serverResponse.equals("bye")) {
System.out.println("服务器端已关闭,断开与服务器端的连接");
break;
}
}
reader.close();
writer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
(2)编写一个服务器端ServerDemo.java程序,它能够响应客户的请求。如
果这个请求的内容是字符串"hello"的话,服务器仅将"welcome!"字符串返回给用
户。否则将用户的话追加到当前目录的文本文件log.txt中,并向用户返回"OK!"。
package org.example;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8001);
System.out.println("服务器已启动,等待客户端连接...");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("客户端已连接");
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String clientMessage = reader.readLine();
if ("hello".equals(clientMessage)) {
writer.write("welcome!");
} else {
File file = new File("E:\\桌面文件\\javatxt文档\\a.txt");
FileWriter fileWriter = new FileWriter(file, true);
BufferedWriter logWriter = new BufferedWriter(fileWriter);
logWriter.write(clientMessage);
logWriter.newLine();
logWriter.close();
writer.write("OK!");
}
writer.newLine();
writer.flush();
reader.close();
writer.close();
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器端
package org.example;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class ClientDemo {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8001);
System.out.println("已连接到服务器端");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("请输入要发送给服务器端的信息:");
String clientMessage = scanner.nextLine();
writer.write(clientMessage);
writer.newLine();
writer.flush();
String serverResponse = reader.readLine();
System.out.println("服务器端消息:" + serverResponse);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
五、实验总结
在本次实验中,我们通过编写服务器端和客户端的Java网络通信程序,加深了对计算机网络基础知识和Java语言网络通信程序类库的理解。通过实践,掌握了网络通信程序的设计方法,包括Socket、ServerSocket等类的使用方法,以及如何进行数据的传输和交互。
六、注意!
我个人觉得程序二跟程序三这两个是配套的,先打开服务器端然后打开客户端机进行连接,接着发打开送端以及接收端然后输入内容再回到客户端或者是服务器端接收信息