Java-网络编程
网络基础
- 网络:两台或多台设备通过一定的物理设备连接起来的构成网络
- 根据网络的覆盖范围不同可将网络分为
- 局域网:覆盖范围最小,一个教室
- 城域网:覆盖范围较大,一个城市
- 广域网:覆盖范围最大,全国或全球,万维网是广域网的代表
IP地址
- IP:用于唯一标识网络中的每台计算机 / 主机
- 查看ip地址命令:ipconfig
- ip地址的标识形式:点分十进制 xx.xx.xx.xx
- 每个十进制数的范围为: 0 ~ 255
- ip地址的组成 = 网络地址 + 主机地址 , 例如:192.168.1.100
- IPv6是互联网工程任务组设计的用于替代IPv4的下一代IP协议,其地址数量号称可以为全世界的每一粒沙子编上一个地址
- 由于IPv4最大的问题在于网络地址资源有限,严重制约了互联网的应用和发展,IPv6的使用,不仅能够解决网络地址资源数量的问题,而且也解决了多种接入设备连入互联网的障碍
IPv4地址分类
- A类: 0 + 7位网络地址 + 24位主机号 : 0.0.0.0 ~ 127.255.255.255
- B类: 1 + 0 + 14位网络地址 + 16位主机号 : 128.0.0.0 ~ 191.255.255.255
- C类: 1 + 1 + 0 + 21位网络地址 + 8位主机号 : 192.0.0.0 ~ 223.255.255.255
- D类: 1 + 1 + 1 + 0 + 28位多播组号 : 224.0.0.0 ~ 239.255.255.255
- E类: 1 + 1 + 1 + 1 + 0 + 27位 : 240.0.0.0 ~ 247.255.255.255
域名和端口
域名
- www.baidu.com
- 好处:为了方便记忆,解决记ip的困难
- 概念:将ip地址映射成域名
端口号
- 概念:用于标识计算机上某个特定的网络程序
- 表示形式:以整数形式呈现,范围为 0 ~ 65535
- 0 ~ 1024 已经被占用,比如 ssh 22, ftp 25 , http 80
- 常见的网络程序端口号:tomcat-8080、mysql-3306、orcale-1521、sqlserver-1433
网络协议
- TCP/IP(Transmission Control Protocol / Internet Protocol 传输控制协议 / 因特互联网协议 网络通讯协议)协议:Internet最基本的协议,Internet国际互联网的基础,由网络层的IP协议和传输层的TCP协议组成
InetAddress类
相关方法
- 获取本机InetAddress对象 getLocalHost
- 根据指定主机名 / 域名获取Ip地址对象 getByName
- 获取InetAddress对象的主机名 getHostName
- 获取InetAddress对象的地址 getHostAddress
public static void main(String[] args) throws UnknownHostException {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost);
System.out.println(InetAddress.getByName("wxy.local"));
System.out.println(InetAddress.getByName("www.baidu.com"));
System.out.println(localHost.getHostName());
System.out.println(localHost.getHostAddress());
}
Socket
- 套接字(Socket)开发网络应用程序被广泛采用,以至于成为事实上的标准
- 通信的两端都要有Socket,是两台机器间通信的端点
- 网络通信其实就是Socket间的通信
- Socket允许程序把网络连接当成一个流,数据在两个Socket间通过IO传输
- 一般主动发起通信的应用程序属客户端,等待通信请求的为服务端
- 拥有TCP编程和UDP编程
TCP编程 △
TCP协议
- 使用TCP协议之前,须先建立TCP连接,形成传输数据通道
- 传输前,采用“三次握手”方式,可靠的
- TCP协议进行通信的两个应用进程:客户端、服务端
- 在连接中可以进行大数据量的传输
- 传输完毕,需释放已建立的链接,效率低
TCP字节流编程
理解1
public class SocketTCP01Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务端,等待端口9999,在监听中,等待连接");
Socket socket = serverSocket.accept();
System.out.println("服务器端-socket = " + socket.getClass());
InputStream inputStream = socket.getInputStream();
byte[] buf = new byte[1024];
int readLen = 0;
while ((readLen = inputStream.read(buf)) != -1) {
System.out.println(new String(buf, 0, readLen));
}
inputStream.close();
socket.close();
serverSocket.close();
}
}
public class SocketTCP01Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
System.out.println("客户端,连接端口9999成功");
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello, server".getBytes(StandardCharsets.UTF_8));
outputStream.close();
socket.close();
System.out.println("客户端退出...");
}
}
理解2
public class SocektTcp02Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
int readLen = 0;
byte[] buf = new byte[1024];
while ((readLen = inputStream.read(buf)) != -1) {
System.out.println(new String(buf, 0, readLen));
}
OutputStream outputStream = socket.getOutputStream();
outputStream.write("I accept your message".getBytes(StandardCharsets.UTF_8));
socket.shutdownOutput();
inputStream.close();
outputStream.close();
socket.close();
serverSocket.close();
}
}
public class SocketTcp02Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello server".getBytes(StandardCharsets.UTF_8));
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
int readLen = 0;
byte[] buf = new byte[1024];
while ((readLen = inputStream.read(buf)) != -1) {
System.out.println(new String(buf, 0, readLen));
}
outputStream.close();
inputStream.close();
socket.close();
}
}
TCP字符流编程
public class SocektTcp03Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(inputStreamReader);
String dataLine = br.readLine();
System.out.println(dataLine);
OutputStream outputStream = socket.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
BufferedWriter bw = new BufferedWriter(outputStreamWriter);
bw.write("I accept your message");
bw.newLine();
bw.flush();
br.close();
bw.close();
socket.close();
serverSocket.close();
}
}
public class SocketTcp03Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
OutputStream outputStream = socket.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
BufferedWriter bw = new BufferedWriter(outputStreamWriter);
bw.write("hello server");
bw.newLine();
bw.flush();
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(inputStreamReader);
String dataLine = br.readLine();
System.out.println(dataLine);
br.close();
bw.close();
socket.close();
}
}
TCP网络编程
上传文件
public class StreamUtils {
public static byte[] streamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = 0;
while ((len = is.read(b)) != -1) {
bos.write(b, 0, len);
}
byte[] array = bos.toByteArray();
bos.close();
return array;
}
public static String streamToString(InputStream is) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line + "\r\n");
}
return builder.toString();
}
public static void main(String[] args) {
}
}
public class TCPFileUploadServer {
public static void main(String[] args) throws IOException {
String storePath = "/Users/xinyu/Desktop/自学/Java/JavaTest/wxy3.jpg";
FileOutputStream fileOutputStream = new FileOutputStream(storePath);
ServerSocket serverSocket = new ServerSocket(9999);
Socket socket = serverSocket.accept();
System.out.println("服务端9999端口等待连接");
BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
byte[] bytes = new StreamUtils().streamToByteArray(bufferedInputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bufferedOutputStream.write(bytes);
OutputStream outputStream = socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write("服务端,收到图片");
bufferedWriter.flush();
socket.shutdownOutput();
bufferedOutputStream.close();
bufferedInputStream.close();
bufferedWriter.close();
fileOutputStream.close();
socket.close();
serverSocket.close();
}
}
public class TCPFileUploadClient {
public static void main(String[] args) throws IOException {
String imgPath = "/Users/xinyu/Desktop/自学/Java/JavaTest/wxy.jpg";
FileInputStream fileInputStream = new FileInputStream(imgPath);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
OutputStream outputStream = socket.getOutputStream();
System.out.println("客户端 与 9999端口 建立连接");
byte[] bytes = new StreamUtils().streamToByteArray(bufferedInputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
bufferedOutputStream.write(bytes);
bufferedInputStream.close();
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
String string = new StreamUtils().streamToString(inputStream);
System.out.println(string);
inputStream.close();
bufferedOutputStream.close();
outputStream.close();
socket.close();
}
}
netstat指令
- netstat -an 可以查看当前主机网络情况,包括端口监听情况和网络连接情况
- netstat -an | more 可以分页显示
- 要求在dos控制台运行
- Listening表示正在被监听
- 外部地址表示,客户端连接到服务端的端口
UDP编程
UDP协议
- 将数据、源、目的封装成数据包,不需要建立连接
- 每个数据包的大小限制在64k内
- 因无需连接,故是不可靠的
- 发送数据结束时,无需释放资源(因为不是面向连接的)速度快
UDP网络编程
- 类DatagramSocket 和 DatagramPacket 实现了基于UDP协议网络协议
- UDP数据报通过数据报套接字 DatagramSocket 发送和接收,系统不保证UDP数据报一定能够安全送到目的地,也不确定什么时候可以抵达
- DatagramPacket 对象封装了UDP数据报,在数据报中包含了发送端的IP地址和端口号以及接收端的IP地址和端口号
- UDP协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和接收方连接
public class UDPReceiverA {
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(9999);
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
datagramSocket.receive(datagramPacket);
int length = datagramPacket.getLength();
byte[] data = datagramPacket.getData();
System.out.println(new String(data, 0, length));
byte[] buf = "好的,明天见".getBytes(StandardCharsets.UTF_8);
DatagramPacket packet =
new DatagramPacket(buf, buf.length, InetAddress.getByName("172.29.226.178"), 9998);
datagramSocket.send(packet);
datagramSocket.close();
System.out.println("A端发送数据成功");
}
}
public class UDPSenderB {
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(9998);
byte[] bytes = "hello 明天吃火锅".getBytes(StandardCharsets.UTF_8);
DatagramPacket datagramPacket =
new DatagramPacket(bytes, 0, bytes.length, InetAddress.getByName("172.29.226.178"), 9999);
datagramSocket.send(datagramPacket);
System.out.println("B端发送信息成功");
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
datagramSocket.receive(packet);
int length = packet.getLength();
byte[] data = packet.getData();
System.out.println(new String(data, 0, length));
datagramSocket.close();
System.out.println("B端接收回复成功");
}
}
Homework
Homework1
public class SocektTcpServerHomework01 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(inputStreamReader);
String dataLine = br.readLine();
System.out.println(dataLine);
String answer = "";
if ("name".equals(dataLine)) {
answer = "wxy";
} else if ("hobby".equals(dataLine)) {
answer = "Java程序";
} else {
answer = "未识别你所描述的话";
}
OutputStream outputStream = socket.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
BufferedWriter bw = new BufferedWriter(outputStreamWriter);
bw.write(answer);
bw.newLine();
bw.flush();
br.close();
bw.close();
socket.close();
serverSocket.close();
}
}
public class SocketTcpClientHomework01 {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
OutputStream outputStream = socket.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
BufferedWriter bw = new BufferedWriter(outputStreamWriter);
Scanner scanner = new Scanner(System.in);
System.out.println("请输入你的问题:");
String question = scanner.next();
bw.write(question);
bw.newLine();
bw.flush();
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(inputStreamReader);
String dataLine = br.readLine();
System.out.println(dataLine);
br.close();
bw.close();
socket.close();
}
}
Homework2
public class UDPReceiverHomework02 {
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(8888);
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
datagramSocket.receive(datagramPacket);
int length = datagramPacket.getLength();
byte[] data = datagramPacket.getData();
String str = new String(data, 0, length);
System.out.println(str);
String answer = "";
if ("四大名著是哪些".equals(str)) {
answer = "红楼梦,三国演义,水浒传,西游记";
} else {
answer = "无法识别";
}
byte[] buf = answer.getBytes(StandardCharsets.UTF_8);
DatagramPacket packet =
new DatagramPacket(buf, buf.length, InetAddress.getByName("172.29.226.178"), 9998);
datagramSocket.send(packet);
datagramSocket.close();
System.out.println("A端发送数据成功");
}
}
public class UDPSenderHomework02 {
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(9998);
Scanner scanner = new Scanner(System.in);
String question = scanner.next();
byte[] bytes = question.getBytes(StandardCharsets.UTF_8);
DatagramPacket datagramPacket =
new DatagramPacket(bytes, 0, bytes.length, InetAddress.getByName("172.29.226.178"), 8888);
datagramSocket.send(datagramPacket);
System.out.println("B端发送信息成功");
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
datagramSocket.receive(packet);
int length = packet.getLength();
byte[] data = packet.getData();
System.out.println(new String(data, 0, length));
datagramSocket.close();
System.out.println("B端接收回复成功");
}
}
homework3
public class Homework03Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(),9999);
Scanner scanner = new Scanner(System.in);
System.out.println("输入需求的文件名:");
String need = scanner.next();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(need);
bw.flush();
socket.shutdownOutput();
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
byte[] bytes = StreamUtils.streamToByteArray(bis);
String storePath = "/Users/xinyu/Desktop/自学/Java/JavaTest/test002.txt";
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(storePath));
bos.write(bytes);
bos.flush();
bos.close();
bis.close();
bw.close();
socket.close();
System.out.println("客户端下载完成");
}
}
public class Homework03Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer need = new StringBuffer();
String data = "";
String download = "";
while ((data = bufferedReader.readLine()) != null) {
need.append(data);
}
download = need.toString();
System.out.println("客户端需要下载的文件名为:" + download);
String filePath = "";
if ("test05".equals(download)) {
filePath += "Study_Java_eleven/src/test05.txt";
} else {
filePath += "Study_Java_eleven/src/test06.txt";
}
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
byte[] bytes = StreamUtils.streamToByteArray(bis);
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(bytes);
bos.flush();
socket.shutdownOutput();
bos.close();
bis.close();
socket.close();
serverSocket.close();
}
}
|