目录
一、网络通信
二、网络
三、 ip地址
四、域名
五、端口号
六、网络通信协议
1、协议(tcp/ip)
2、TCP和UDP
七、InetAddress类
八、Socket
1、基本介绍:
2、TCP网络通信编程
3、UDP网络通信编程(了解即可,较冷)
九、作业
一、网络通信
1、概念:两台设备之间通过网络实现数据传输
2、网络通信:将数据通过网络从一台设备传输到另一台设备
3、java.net包下提供了一系列的类或接口,供程序员使用,完成网络通信
二、网络
1、概念:两台或多台设备通过一定物理设备连接起来构成了网络
2、根据网络的覆盖范围不同,对网络进行分类:
局域网:覆盖范围最小,仅仅覆盖一个教室或一个机房
城域网:覆盖范围较大,可以覆盖一个城市
广域网:覆盖范围最大,可以覆盖全国,甚至全球,万维网是广域网的代表
三、 ip地址
1、 概念:用于唯一标识网络中的每台计算机
2 、查看ip地址:ipconfig
3 、ip地址的表示形式:点分十进制 XX.XX.XX.XX
4、每一个十进制数的范围:0~255
5、ip地址的组成=网络地址+主机地址,比如:192.168.16.69
6、IPv6是互联网工程任务组设计的用于替代IPv4的下一代IP协议,其地址数量号称可以为全世界的每一粒沙子编上一个地址[1]。
7、由于IPv4最大的问题在于网络地址资源有限,严重制约了互联网的应用和发展。IPv6
的使用,不仅能解决网络地址资源数量的问题,而且也解决了多种接入设备连入互联网
的障碍
四、域名
1、www.baidu.com
2、好处:为了方便记忆,解决记ip的困难
3、概念:将ip地址映射成域名
五、端口号
1、概念:用于标识计算机上某个特定的网络程序
2、表示形式:以整数形式,范围0~65535
3、0~1024已经被占用,比如ssh 22, ftp 21, smtp 25, http 80
4、常见的网络程序端口号:
tomcat: 8080
mysql: 3306
oracle: 1521
sqlserver: 1433
ip用来找你家的房子,端口则是找进你家的门
六、网络通信协议
1、协议(tcp/ip)
TCP/IP(Transmission Control Protocol/Internet Protocol)的简写
传输控制协议/因特网互联协议,又叫网络通讯协议
这个协议是Internet最基本的协议,简单地说,就是由网络层的IP协议和传输层的TCP协议组成的
2、TCP和UDP
(1)TCP协议
1)使用TCP协议前,须先建立TCP连接,形成传输数据通道
2)传输前,采用“三次握手”方式,是可靠的
在吗?
在。
上号
3)TCP协议进行通信的两个应用进程:客户端、服务端
4)在连接中可进行大数据量的传输
5)传输完毕,需释放已建立的连接,效率低
(2)UDP协议:(用户数据协议)
1)将数据、源、目的封装成数据包,不需要建立连接
2)每个数据报的大小限制在64K内,不适合传输大量数据
3)因无需连接,故是不可靠的
4)发送数据结束时无需释放资源(因为不是面向连接的),速度快
5)直接发信息过去,不管对方收没收到
七、InetAddress类
1、相关方法
(1)获取本机InetAddress对象getLocalHost
(2)根据指定主机名/域名获取ip地址对象getByName
(3)获取InetAddress对象的主机名getHostName
(4)获取InetAddress对象的地址getHostAddress
package api;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class API_ {
public static void main(String[] args) throws UnknownHostException {
//1.获取本机的InetAddress对象
InetAddress localHost=InetAddress.getLocalHost();
System.out.println(localHost);
//输出:DESKTOP-FJFA3NA/10.0.133.145
//2.根据指定主机名,获取InetAddress对象
InetAddress host1=InetAddress.getByName("DESKTOP-FJFA3NA");
System.out.println(host1);
//输出:DESKTOP-FJFA3NA/10.0.133.145
//3.根据域名返回InetAddress对象,如返回百度对应的ip
InetAddress host2=InetAddress.getByName("www.baidu.com");
System.out.println(host2);
//输出:www.baidu.com/112.80.248.75
//4.通过InetAddress对象,获取对应的地址
String hostAddress=host2.getHostAddress();
System.out.println("host2对应的ip:"+hostAddress);
//输出:host2对应的ip:112.80.248.76
//5.通过InetAddress对象,获取对应的主机名/或者对应的域名
String hostName=host2.getHostName();
System.out.println("host2对应的主机名/域名:"+hostName);
//输出:host2对应的主机名/域名:www.baidu.com
}
}
八、Socket
1、基本介绍:
(1)套接字(Socket)开发网络应用程序被广泛采用,以至于成为事实上标准
(2)通信的两端都要有Socket,是两台机器间通信的端点
(3)网络通信其实就是Socket间的通信
(4)Socket允许程序把网络连接当成一个流,数据在两个Socket间通过IO传输
(5)一般主动发起通信的应用程序属客户端,等待通信请求的为服务端
可以把套接字理解成车站,人流(数据)只能在车站上下车
2、TCP网络通信编程
(1)基本介绍:
1)基于客户端——服务端的网络通信
2)底层使用的是TCP/IP协议
3)应用场景举例:客户端发送数据,服务端接受并显示在控制台
4)基于Socket的TCP编程
(2)
思路分析:
难点:客户端和服务端两头都要考虑
//服务端
package socket;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketTCP01Server {
public static void main(String[] args) throws IOException {
//1、在本机的9999端口监听,等待连接,要求在本机上没有其它服务在监听9999
//serverSocket可以通过accept()返回多个socket对象[多个客户端连接服务器的并发]
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务端,在9999端口监听,等待连接。。。");
//2、如果有客户端连接,则会返回Socket对象,程序继续,客户端和服务器端各有一个socket对象
Socket socket=serverSocket.accept();
System.out.println("服务端 socket:"+socket.getClass());
//3、通过socket.getInputStream()读取客户端写入到数据通道的数据,显示
InputStream inputStream=socket.getInputStream();
//4、IO读取
byte[] buf=new byte[1024];
int readLen=0;
while((readLen=inputStream.read(buf))!=-1){
//根据读取到的实际长度,显示内容
System.out.println(new String(buf,0,readLen));
}
//5、关闭流和socket
inputStream.close();
socket.close();
serverSocket.close();
}
}
//服务端,在9999端口监听,等待连接。。。
//服务端 socket:class java.net.Socket
//hello,server
//注意:先运行服务端,再运行客户端,这本该是在两台机器上执行的
//客户端
package socket;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketTCP01Client {
public static void main(String[] args) throws IOException {
//1、连接服务器(ip,端口)
//连接本机的9999端口,如果连接成功,返回Socket对象
Socket socket = new Socket(InetAddress.getLocalHost(),9999);
System.out.println("客户端 socket返回:"+socket.getClass());
//2、连接上后,生成Socket,通过socket.getOutputStream()
//得到和socket对象关联的输出流对象
OutputStream outputStream=socket.getOutputStream();
//3、通过输出流,写入数据到数据通道
outputStream.write("hello,server".getBytes());
//4、关闭流
outputStream.close();
socket.close();
System.out.println("客户端退出了");
}
}
//客户端 socket返回:class java.net.Socket
//客户端退出了
(3)
//我的代码
package socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketTCP02Server {
public static void main(String[] args) throws IOException {
//1、编写一个服务器端,在9999端口监听
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务端,在9999端口监听,等待连接。。。");
//2、有客户端连接
Socket socket=serverSocket.accept();
Socket socket1=serverSocket.accept();
System.out.println("服务器和客户端连接成功。。。");
//3、读取数据
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));
}
socket.close();
inputStream.close();
//4、发送数据
OutputStream outputStream=socket1.getOutputStream();
outputStream.write("hello,client".getBytes());
//5、关闭
serverSocket.close();
socket1.close();
outputStream.close();
System.out.println("服务端退出。。。");
}
}
//服务端,在9999端口监听,等待连接。。。
//服务器和客户端连接成功。。。
//hello,server
//服务端退出。。。
package socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketTCP02Client {
public static void main(String[] args) throws IOException {
//1、编写一个客户端,连接到服务器端,
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
Socket socket1=new Socket(InetAddress.getLocalHost(),9999);
System.out.println("客户端连接服务端成功。。。");
//2、发送“hello,server”,
OutputStream outputStream=socket.getOutputStream();
outputStream.write("hello,server".getBytes());
socket.close();
outputStream.close();
//3、读取数据
InputStream inputStream=socket1.getInputStream();
byte[] buf = new byte[1024];
int readLen=0;
while((readLen=inputStream.read(buf))!=-1){
System.out.println(new String(buf,0,readLen));
}
//4、关闭
socket1.close();
inputStream.close();
System.out.println("客户端退出。。。");
}
}
//客户端连接服务端成功。。。
//hello,client
//客户端退出。。。
//老师的代码:
package socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketTCP02Server {
public static void main(String[] args) throws IOException {
//1、编写一个服务器端,在9999端口监听
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务端,在9999端口监听,等待连接。。。");
//2、有客户端连接
Socket socket=serverSocket.accept();
System.out.println("服务器和客户端连接成功。。。");
//3、读取数据
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));
}
//设置结束标记
socket.shutdownInput();
//4、发送数据
OutputStream outputStream=socket.getOutputStream();
outputStream.write("hello,client".getBytes());
//5、关闭
serverSocket.close();
socket.close();
outputStream.close();
inputStream.close();
System.out.println("服务端退出。。。");
}
}
//服务端,在9999端口监听,等待连接。。。
//服务器和客户端连接成功。。。
//hello,server
//服务端退出。。。
package socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketTCP02Client {
public static void main(String[] args) throws IOException {
//1、编写一个客户端,连接到服务器端,
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
System.out.println("客户端连接服务端成功。。。");
//2、发送“hello,server”,
OutputStream outputStream=socket.getOutputStream();
outputStream.write("hello,server".getBytes());
//设置结束标记
socket.shutdownOutput();
//3、读取数据
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));
}
//4、关闭
socket.close();
inputStream.close();
outputStream.close();
System.out.println("客户端退出。。。");
}
}
//客户端连接服务端成功。。。
//hello,client
//客户端退出。。。
(4)
//我的代码:
package socket;
public abstract class Reader_ {
public void server(){}
public void client(){}
}
package socket;
public class ServerReader extends Reader_{
public void server(){
System.out.println("hello,client");
}
}
package socket;
public class ClientReader extends Reader_{
public void client(){
System.out.println("hello,server");
}
}
package socket;
public class BufferedReader_ extends Reader_{
private Reader_ reader_;
public BufferedReader_(Reader_ reader_) {
this.reader_ = reader_;
}
public void server(){
reader_.server();
}
public void client(){
reader_.client();
}
}
package socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketTCP02Server {
public static void main(String[] args) throws IOException {
//1、编写一个服务器端,在9999端口监听
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务端,在9999端口监听,等待连接。。。");
//2、有客户端连接
Socket socket=serverSocket.accept();
System.out.println("服务器和客户端连接成功。。。");
//3、读取数据
BufferedReader_ bufferedReader_ = new BufferedReader_(new ServerReader());
bufferedReader_.server();
//设置结束标记
socket.shutdownInput();
//5、关闭
serverSocket.close();
socket.close();
System.out.println("服务端退出。。。");
}
}
//服务端,在9999端口监听,等待连接。。。
//服务器和客户端连接成功。。。
//hello,server
//服务端退出。。。
package socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketTCP02Client {
public static void main(String[] args) throws IOException {
//1、编写一个客户端,连接到服务器端,
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
System.out.println("客户端连接服务端成功。。。");
BufferedReader_ bufferedReader_ = new BufferedReader_(new ClientReader());
bufferedReader_.client();
//4、关闭
socket.close();
System.out.println("客户端退出。。。");
}
}
//客户端连接服务端成功。。。
//hello,client
//客户端退出。。。
//老师的代码:
package socket;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketTCP02Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务端,在9999端口监听,等待连接。。。");
Socket socket=serverSocket.accept();
System.out.println("服务器和客户端连接成功。。。");
InputStream inputStream=socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String s=bufferedReader.readLine();
System.out.println(s);
OutputStream outputStream=socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write("hello, client 字符流");
bufferedWriter.newLine();//插入一个换行符,表示回复内容的结束
bufferedWriter.flush();//手动刷新
bufferedWriter.close();//关闭外层流
bufferedReader.close();//关闭外层流
socket.close();
serverSocket.close();
//一般是后打开的先关闭
System.out.println("服务端退出。。。");
}
}
//服务端,在9999端口监听,等待连接。。。
//服务器和客户端连接成功。。。
//hello,server
//服务端退出。。。
package socket;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class SocketTCP02Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
System.out.println("客户端连接服务端成功。。。");
OutputStream outputStream=socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write("hello,server 字符流");
bufferedWriter.newLine();//插入一个换行符,表示写入的内容结束,注意,要求对方使用readLine()
bufferedWriter.flush();//如果使用的字符流,需要手动刷新,否则数据不会写入数据通道
InputStream inputStream=socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String s=bufferedReader.readLine();
System.out.println(s);
bufferedReader.close();//关闭外层流
bufferedWriter.close();//关闭外层流
socket.close();
System.out.println("客户端退出。。。");
}
}
//客户端连接服务端成功。。。
//hello,client
//客户端退出。。。
(5)
//我的代码:
package socket;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketTCP03Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket=new ServerSocket(8888);
System.out.println("服务端,在8888端口监听,等待连接。。。");
Socket socket=serverSocket.accept();
System.out.println("服务端和客户端连接成功。。。");
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(socket.getInputStream().toString()));
String destPath="D:\\java-idea-2022.10.26\\Charpter21\\src";
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destPath));
bufferedOutputStream.write(bufferedInputStream.read());
bufferedOutputStream.close();
socket.shutdownInput();
OutputStream outputStream=socket.getOutputStream();
outputStream.write("收到图片".getBytes());
outputStream.close();
socket.close();
}
}
package socket;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.ServerSocket;
public class SocketTCP03Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
System.out.println("客户端连接服务端成功。。。");
//向服务端发送信息
String FilePath="e:\\金1.png";
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(FilePath));
bufferedOutputStream.
//接收服务端的回复
String s=null;
InputStream inputStream=socket.getInputStream();
byte[] buf=new byte[1024];
int readLen=0;
while((readLen=inputStream.read(buf))!=-1){
s = new String(buf, 0, readLen);
}
//收到回复后退出
if(s.equals("收到图片")){
inputStream.close();
socket.close();
System.out.println("客户端退出。。。");
}
}
}
//老师的代码:
package com.hspedu.upload;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class StreamUtils {
/**
* 功能:将输入流转换成byte[],即可以把文件的内容读入到byte[]
* @param is
* @return
* @throws Exception
*/
public static byte[] streamToByteArray(InputStream is) throws Exception {
// 创建输出流对象
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// 字节数组
byte[] b = new byte[1024];
int len;
while ((len = is.read(b)) != -1) {
// 循环读取
// 把读取到的数据,写入 bos
bos.write(b, 0, len);
}
//将bos转成字节数组
byte[] array = bos.toByteArray();
bos.close();
return array;
}
/**
* 功能:将InputStream转换成String
* @param is
* @return
* @throws Exception
*/
public static String streamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\r\n");
}
return builder.toString();
}
}
package upload;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPFileUploadServer {
public static void main(String[] args) throws Exception {
//服务器在本机监听8888端口
ServerSocket serverSocket=new ServerSocket(8888);
System.out.println("服务端在8888端口监听。。。");
//等待连接
Socket socket=serverSocket.accept();
//读取客户端发送的数据,通过Socket得到输入流
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
byte[] bytes=StreamUtils.streamToByteArray(bis);
//将得到的bytes数组,写入到指定的路径,就得到一个文件了
String destFilePath="src\\金贤镇.jpeg";
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
bos.write(bytes);
//向客户端回复“收到图片”,通过socket获取到输出流(字符)
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("收到图片");
writer.flush();//把内容刷新到数据通道
socket.shutdownOutput();//设置写入结束标记
writer.close();
bos.close();
bis.close();
socket.close();
serverSocket.close();
}
}
package upload;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPFileUploadClient {
public static void main(String[] args) throws Exception {
//客户端连接服务端,得到socket对象
Socket socket = new Socket(InetAddress.getLocalHost(),8888);
//创建读取磁盘文件的输入流
String filePath="e:\\金贤镇.jpeg";
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
//bytes就是filePath对应的字节数组
byte[] bytes=StreamUtils.streamToByteArray(bis);
//通过socket获取输出流,将bytes数据发送给服务器
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(bytes);//将文件对应的字节数组的内容写入到数据通道
bis.close();
socket.shutdownOutput();//设置写入数据的结束标记
//接收从服务端回复的消息
InputStream inputStream=socket.getInputStream();
//使用StreamUtils的方法,直接将inputStream读取到的内容转成字符串
String s=StreamUtils.streamToString(inputStream);
System.out.println(s);
bos.close();
socket.close();
}
}
温暖牌小贴士:写网络编程时,要注意有一个整体的思路,否则很容易混乱
(6)netstat指令:
1)netstat-an可以查看当前主机网络情况,包括端口监听情况和网络连接情况
2)netstat-an | more可以分页显示
3)要求在dos控制台下执行win+r
说明:
· Listening表示某个端口在监听
· 如果有一个外部程序(客户端)连接到该端口,就会显示一条连接信息
· 可以输入ctrl+c退出指令
补:查看ip地址的cmd命令:ipconfig
(7)细节:
1)当客户端连接到服务端后,实际上客户端也是通过一个端口和服务端进行通讯的,这个端口是TCP/IP来分配的
2) 程序验证+netstat [B站第675集]
3、UDP网络通信编程(了解即可,较冷)
(1)基本介绍:
1)类DatagramSocket和DatagramPacket [数据包 / 数据报] 实现了基于UDP协议网络程序
2)UDP数据报通过数据报套接字DatagramSocket发送和接收,系统不保证UDP数据报一定能够安全送到目的地,也不能确定什么时候可以抵达
3)DatagramPacket对象封装了UDP数据报,在数据报中包含了发送端的ip地址和端口号以及接收端的ip地址和端口号
4)UDP协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和接收方的连接
(2)基本流程:
1)核心的两个类 / 对象 DatagramSocket与DatagramPacket
2)建立发送端,接收端(没有服务端和客户端的概念)
3)发送数据前,建立数据包,DatagramPacket对象
4)调用 DatagramSocket的发送、接收方法
5)关闭DatagramSocket
(3)
package udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPReceiverA {
public static void main(String[] args) throws IOException {
//创建一个DatagramPocket对象,准备在9999接收数据
DatagramSocket socket = new DatagramSocket(9999);
//构建一个DatagramPacket对象,准备接收数据,一个数据包最大64K
byte[] buf=new byte[1024];
DatagramPacket packet=new DatagramPacket(buf,buf.length);
//调用接收方法,将通过网络传输的DatagramPacket对象填充到packet对象
//当有数据包发送到本机的9999端口时,就会接收到数据
//如果没有,就会阻塞等待
System.out.println("接收端A等待接收数据。。。");
socket.receive(packet);
//可以把packet进行拆包,取出数据,并显示
int length=packet.getLength();//实际接收到的数据字节长度
byte[] data=packet.getData();//接收到数据
String s=new String(data,0,length);
System.out.println(s);
//回复
data="好的,明天见~".getBytes();
packet = new DatagramPacket(data, data.length, InetAddress.getByName("10.0.57.212"), 9998);//注意端口
socket.send(packet);
//关闭
socket.close();
System.out.println("A端退出。。。");
}
}
//接收端A等待接收数据。。。
//hello 明天吃火锅去~
//A端退出。。。
package socket;
import java.io.IOException;
import java.net.*;
public class UDPSenderB {
public static void main(String[] args) throws IOException {
//创建DatagramSocket对象,准备在9998端口发送和接收数据
//此端口最好不要与UDPReceiverA的端口一样
DatagramSocket socket = new DatagramSocket(9998);
//将需要发送的数据,封闭到DatagramPacket对象
byte[] data="hello 明天吃火锅去~".getBytes();
//封装的DatagramPacket对象:data内容字节数组,data.length,主机(IP),端口
DatagramPacket packet = new DatagramPacket(
data, data.length, InetAddress.getByName("10.0.57.212"), 9999);
socket.send(packet);
//接收A回复的信息
byte[] buf=new byte[1024];
packet=new DatagramPacket(buf,buf.length);
socket.receive(packet);
int length=packet.getLength();
data=packet.getData();
String s=new String(data,0,length);
System.out.println(s);
socket.close();
System.out.println("B端退出。。。");
}
}
//好的,明天见~
//B端退出。。。
九、作业
1、
//我的代码:
package homework;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Homework01Server {
public static void main(String[] args) throws IOException {
ServerSocket serversocket=new ServerSocket(9999);
System.out.println("服务器在9999端口监听。。。");
Socket socket= serversocket.accept();
InputStream inputStream=socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String s=bufferedReader.readLine();
System.out.println(s);
OutputStream outputStream = socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
if(s.equals("name")) {
bufferedWriter.write("我是nova");
}else{
bufferedWriter.write("你说啥呢");
}
bufferedWriter.newLine();
bufferedWriter.flush();
inputStream=socket.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
s=bufferedReader.readLine();
System.out.println(s);
outputStream = socket.getOutputStream();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
if(s.equals("hobby")) {
bufferedWriter.write("编写java程序");
}else{
bufferedWriter.write("你说啥呢");
}
bufferedWriter.newLine();
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
socket.close();
serversocket.close();
}
}
//服务器在9999端口监听。。。
//name
//hobby
package homework;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Homework01Client {
public static void main(String[] args) throws IOException {
Socket socket=new Socket(InetAddress.getLocalHost(),9999);
System.out.println("客户端连接服务端成功。。。");
OutputStream outputStream=socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write("name");
bufferedWriter.newLine();
bufferedWriter.flush();
InputStream inputStream=socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String s=bufferedReader.readLine();
System.out.println(s);
outputStream=socket.getOutputStream();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write("hobby");
bufferedWriter.newLine();
bufferedWriter.flush();
inputStream=socket.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
s=bufferedReader.readLine();
System.out.println(s);
bufferedReader.close();
bufferedWriter.close();
socket.close();
}
}
//客户端连接服务端成功。。。
//我是nova
//编写java程序
//老师的代码:
package homework;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Homework01Server {
public static void main(String[] args) throws IOException {
ServerSocket serversocket=new ServerSocket(9999);
System.out.println("服务器在9999端口监听。。。");
Socket socket= serversocket.accept();
InputStream inputStream=socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String s=bufferedReader.readLine();
String answer="";
if("name".equals(s)){
answer="我是nova";
}else if("hobby".equals(s)){
answer="编写java程序";
}else{
answer="你说的啥子";
}
OutputStream outputStream = socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(answer);
bufferedWriter.newLine();
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
socket.close();
serversocket.close();
}
}
package homework;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Homework01Client {
public static void main(String[] args) throws IOException {
Socket socket=new Socket(InetAddress.getLocalHost(),9999);
System.out.println("客户端连接服务端成功。。。");
OutputStream outputStream=socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
Scanner scanner=new Scanner(System.in);
System.out.println("请输入你的问题:");
String question=scanner.next();
bufferedWriter.write(question);
bufferedWriter.newLine();
bufferedWriter.flush();
InputStream inputStream=socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String s=bufferedReader.readLine();
System.out.println(s);
bufferedReader.close();
bufferedWriter.close();
socket.close();
}
}
//客户端连接服务端成功。。。
//请输入你的问题:
//name
//我是nova
//进化版的,可以一次问多个问题
package homework;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Homework01Server {
public static void main(String[] args) throws IOException {
ServerSocket serversocket=new ServerSocket(9999);
System.out.println("服务器在9999端口监听。。。");
Socket socket= serversocket.accept();
InputStream inputStream = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String s =" ";
OutputStream outputStream = socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
while(!(s.equals("end"))) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
s = bufferedReader.readLine();
String answer = "";
if ("name".equals(s)) {
answer = "我是nova";
} else if ("hobby".equals(s)) {
answer = "编写java程序";
} else {
answer = "你说的啥子";
}
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(answer);
bufferedWriter.newLine();
bufferedWriter.flush();
}
bufferedWriter.close();
bufferedReader.close();
socket.close();
serversocket.close();
}
}
package homework;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Homework01Client {
public static void main(String[] args) throws IOException {
Socket socket=new Socket(InetAddress.getLocalHost(),9999);
System.out.println("客户端连接服务端成功。。。");
String question=" ";
OutputStream outputStream=socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
InputStream inputStream = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while(!(question.equals("end"))) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入你的问题:");
question = scanner.next();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(question);
bufferedWriter.newLine();
bufferedWriter.flush();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String s = bufferedReader.readLine();
System.out.println(s);
}
bufferedReader.close();
bufferedWriter.close();
socket.close();
}
}
//客户端连接服务端成功。。。
//请输入你的问题:
//name
//我是nova
//请输入你的问题:
//hobby
//编写java程序
//请输入你的问题:
//h
//你说的啥子
//请输入你的问题:
//end
//你说的啥子
//
//进程已结束,退出代码0
2、
//我的代码:
package homework02;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class Homework02ReceiverA {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9999);
//建包,准备装数据
byte[] buf=new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
System.out.println("A端等待接收数据。。。");
socket.receive(packet);
//拆包,取数据
int length=packet.getLength();
byte[] data=packet.getData();
String s=new String(data,0,length);
System.out.println(s);
//回复
if(s.equals("四大名著是哪些")) {
data = "四大名著是《红楼梦》……".getBytes();
}else{
data="what?".getBytes();
}
packet=new DatagramPacket(data,data.length, InetAddress.getByName("192.168.43.227"),9998);
socket.send(packet);
}
}
//A端等待接收数据。。。
//四大名著是哪些
package homework02;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.*;
public class Homework02SenderB {
public static void main(String[] args) throws IOException {
DatagramSocket socket=new DatagramSocket(9998);
System.out.println("B端准备发送数据。。。");
//打包数据,发送
byte[] data="四大名著是哪些".getBytes();
DatagramPacket packet = new DatagramPacket(
data, data.length, InetAddress.getByName("192.168.43.227"), 9999);
socket.send(packet);
//接收回复
byte[] buf=new byte[1024];
packet=new DatagramPacket(buf,buf.length);
socket.receive(packet);
int length=packet.getLength();
data=packet.getData();
String s=new String(data,0,length);
System.out.println(s);
socket.close();
System.out.println("B端退出。。。");
}
}
//B端准备发送数据。。。
//四大名著是《红楼梦》……
//B端退出。。。
//老师的代码:
package homework02;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class Homework02ReceiverA {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9999);
//建包,准备装数据
byte[] buf=new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
System.out.println("A端等待接收数据。。。");
socket.receive(packet);
//拆包,取数据
int length=packet.getLength();
byte[] data=packet.getData();
String s=new String(data,0,length);
String answer=" ";
//回复
if("四大名著是哪些".equals(s)) {
answer = "四大名著是《红楼梦》……";
}else{
answer="what?";
}
data=answer.getBytes();
packet=new DatagramPacket(data,data.length, InetAddress.getByName("192.168.43.227"),9998);
socket.send(packet);
socket.close();
System.out.println("A端退出。。。");
}
}
package homework02;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class Homework02SenderB {
public static void main(String[] args) throws IOException {
DatagramSocket socket=new DatagramSocket(9998);
System.out.println("B端准备发送数据。。。");
Scanner scanner = new Scanner(System.in);
System.out.println("请输入你的问题:");
String question=scanner.next();
byte[] data="四大名著是哪些".getBytes();
DatagramPacket packet = new DatagramPacket(
data, data.length, InetAddress.getByName("192.168.43.227"), 9999);
socket.send(packet);
//接收回复
byte[] buf=new byte[1024];
packet=new DatagramPacket(buf,buf.length);
socket.receive(packet);
int length=packet.getLength();
data=packet.getData();
String s=new String(data,0,length);
System.out.println(s);
socket.close();
System.out.println("B端退出。。。");
}
}
//B端准备发送数据。。。
//请输入你的问题:
//四大名著是哪些
//四大名著是《红楼梦》……
//B端退出。。。
3、
//我的代码(我尽力了)
package homework03;
import com.sun.source.tree.Scope;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Homework03Server {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务端在8888端口监听。。。");
Socket socket=serverSocket.accept();
//接收数据
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
String filePath=StreamUtils.streamToString(bis);
String defaultFilePath="e:\\岁月.mp3";//默认的音乐文件
File file=new File(filePath);
if(file.exists()){
bis=new BufferedInputStream(new FileInputStream(file));
}else{
bis=new BufferedInputStream(new FileInputStream(defaultFilePath));
}
//返回转成字节数组的文件数据
byte[] bytes=StreamUtils.streamToByteArray(bis);
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(bytes);
//关闭
bos.close();
bis.close();
socket.close();
serverSocket.close();
}
}
package homework03;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.rmi.server.UnicastRemoteObject;
public class Homework03Client {
public static void main(String[] args) throws Exception {
Socket socket=new Socket(InetAddress.getLocalHost(),8888);
String filePath="e:\\百战成诗.mp3";
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
//第一层,将要发送的文件转成字节数组
byte[] bytes= StreamUtils.streamToByteArray(bis);
//第二层,用输出流发送字节数据
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(bytes);
//设置写入数据的结束标记
socket.shutdownOutput();
//接收回复的信息,写入到新的位置
bis=new BufferedInputStream(socket.getInputStream());
bytes=StreamUtils.streamToByteArray(bis);
String destFilePath="e:\\岁月2.mp3";
bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
bos.write(bytes);
bos.close();
bis.close();
socket.close();
}
}
//老师的代码:
package homework03;
import com.sun.source.tree.Scope;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Homework03Server {
public static void main(String[] args) throws Exception {
//监听9999端口
ServerSocket serverSocket = new ServerSocket(9999);
//等待客户端连接
System.out.println("服务端在9999端口监听,等待下载文件。。。");
Socket socket=serverSocket.accept();
//读取客户端发送要下载的文件名
//这里使用while读取文件名时,考虑到了将来客户端发送的数据较大的情况
InputStream inputStream=socket.getInputStream();
byte[] b=new byte[1024];
int len=0;
String downLoadFileName="";
while((len=inputStream.read(b))!=-1){
downLoadFileName+=new String(b,0,len);
}
System.out.println("客户端希望下载文件名:"+downLoadFileName);
String resFileName="";
if("百战成诗".equals(downLoadFileName)){
resFileName="src\\百战成诗.mp3";
}else{
resFileName="src\\岁月.mp3";
}
//创建一个输入流,读取文件
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(resFileName));
//使用工具类StreamUtils,读取文件到一个字节数组
byte[] bytes=StreamUtils.streamToByteArray(bis);
//得到Socket关联的输出流
BufferedOutputStream bos=new BufferedOutputStream(socket.getOutputStream());
//写入到数据通道,返回给客户端
bos.write(bytes);
socket.shutdownOutput();
//关闭
bos.close();
bis.close();
inputStream.close();
socket.close();
serverSocket.close();
System.out.println("服务端退出。。。");
}
}
package homework03;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Scanner;
public class Homework03Client {
public static void main(String[] args) throws Exception {
//接收用户输入,指定下载文件名
Scanner scanner = new Scanner(System.in);
System.out.println("请输入下载文件名:");
String downLoadFileName=scanner.next();
//客户端连接服务端,准备发送
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
//获取和Socket关联的输出流
OutputStream outputStream=socket.getOutputStream();
outputStream.write(downLoadFileName.getBytes());
//设置写入结束的标志
socket.shutdownOutput();
//读取服务端返回的文件(字节数据)
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
byte[] bytes=StreamUtils.streamToByteArray(bis);
//得到一个输出流,准备将bytes写入到磁盘文件
String filePath="e:\\"+downLoadFileName+".mp3";
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
bos.write(bytes);
//关闭
bos.close();
bis.close();
outputStream.close();
socket.close();
System.out.println("客户端下载完毕,退出。。。");
}
}
//读取信息有点棘手