1. 计算机网络概念
??计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接(有线性、无线)起来,在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统。
-
网络编程的目的: ??1.传播交流信息 ??2.数据交换、通信 -
网络编程中两个主要问题: ??1.如何准确定位到网络上的一台或多台主机 ??2.找到主机之后如何进行通信 -
网络编程中的要素: ??1.IP 和 端口号 ??2.网络通信协议 -
Java 万物皆对象
JavaWeb : 网页编程 B/S架构 网络编程: TCP/IP C/S架构
TCP/IP模型的层次结构及各层的主要协议:
2. IP
2.1 概念
??IP地址是IP协议提供的一种统一的地址格式,互联网上的每一个网络和每一台主机分配一个逻辑地址,以此来屏蔽物理地址的差异。
2.2 IP地址分类
IPv4地址分类: IP地址使用范围:
2.3 InetAddress类
- java.net.InetAddress
- 此类表示互联网协议(IP)地址
public class TestInetAddress {
public static void main(String[] args) {
try {
InetAddress address1 = InetAddress.getByName("127.0.0.1");
InetAddress address2 = InetAddress.getByName("localhost");
InetAddress address3 = InetAddress.getLocalHost();
System.out.println(address1);
System.out.println(address2);
System.out.println(address3);
InetAddress name = InetAddress.getByName("www.baidu.com");
System.out.println(name);
System.out.println(name.getCanonicalHostName());
System.out.println(name.getHostAddress());
System.out.println(name.getHostName());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
运行结果:
/127.0.0.1
localhost/127.0.0.1
DESKTOP-OQ029O9/172.21.228.215
www.baidu.com/180.101.49.11
180.101.49.11
180.101.49.11
www.baidu.com
3. 端口
3.1 概念
??端口标识的是主机中的应用进程,端口号只具有本地意义,标识本计算机应用层中的各进程,在因特网中不同计算机的相同端口号是没有联系的。
3.2 端口分类
1.服务器端
- 公有端口:0-1023
- 程序注册端口:1024-49151,分配给用户或者程序。
???Tomcat:8080 ???Mysql:3306 ???Oracle:1521
2.客户端
- 动态、私有:49152-65535
- 也称短暂端口号(临时端口),通信结束后,刚用过的客户端口号就不复存在,该端口号可供其他客户进程以后使用。
3.3 查看端口命令
netstat -ano #查看所有端口
netstat -ano | findstr "5900" #查看指定的端口
tasklist | findstr "8696" #查看指定端口的进程
Ctrl + Shift + Esc
3.4 InetSocketAddress类
- java.net.InetSocketAddress
- InetSocketAddress(InetAddress addr, int port):根据 IP 地址和端口号创建套接字地址。
- InetSocketAddress(String hostname, int port):根据主机名和端口号创建套接字地址。
public class TestInetSocketAddress {
public static void main(String[] args) {
InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8080);
InetSocketAddress socketAddress1 = new InetSocketAddress("localhost", 8080);
System.out.println(socketAddress);
System.out.println(socketAddress1);
System.out.println("====================");
System.out.println(socketAddress.getAddress());
System.out.println(socketAddress.getHostName());
System.out.println(socketAddress.getHostString());
System.out.println(socketAddress.getPort());
}
}
运行结果:
/127.0.0.1:8080
localhost/127.0.0.1:8080
====================
/127.0.0.1
127.0.0.1
127.0.0.1
8080
4. 通信协议
TCP/IP协议簇:实际上是一组协议 重要: ??TCP:用户传输协议 ??UDP:用户数据报协议 ?? TCP: 面向连接,适用于可靠性更重要场合,如文件传输协议(FTP)、超文本传输协议(HTTP)、远程登陆(TELNET)等。 UDP: 无连接,非可靠传输层协议,协议简单,执行速度快,实时性号,应用主要包括小文件传送协议(TFTP)、DNS、SNMP和实时传输协议(RTP)。
4.1 TCP
TCP:三次握手、四次挥手 客户端:1.建立连接 ????2.发送消息
public class TcpClientDemo1 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os= null;
try {
InetAddress severIP = InetAddress.getByName("127.0.0.1");
int port=9999;
socket = new Socket(severIP, port);
os=socket.getOutputStream();
os.write("hello world!".getBytes());
} catch (Exception 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();
}
}
}
}
}
服务器:1.建立服务连接的端口 ServerSocket ????2.等待用户的连接 accept ????3.接收用户信息
public class TcpServerDemo1 {
public static void main(String[] args) {
ServerSocket serverSocket =null;
Socket socket =null;
InputStream is = null;
ByteArrayOutputStream baos =null;
try {
serverSocket = new ServerSocket(9999);
socket = serverSocket.accept();
is = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
TCP实现文件上传 客户端:
public class TcpClientDemo2 {
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
OutputStream os=socket.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(new File("picture.jpg"));
byte[] buffer = new byte[1024];
int len;
while ((len=fileInputStream.read(buffer))!=-1){
os.write(buffer,0,len);
}
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2;
while ((len2=inputStream.read(buffer2))!=-1){
byteArrayOutputStream.write(buffer2,0,len);
}
System.out.println(byteArrayOutputStream.toString());
byteArrayOutputStream.close();
inputStream.close();
fileInputStream.close();
os.close();
socket.close();
}
}
服务器:
public class TcpServerDemo2 {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9000);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(new File("receive.jpg"));
byte[] buffer = new byte[1024];
int len;
while ((len=inputStream.read(buffer))!=-1){
fileOutputStream.write(buffer,0,len);
}
OutputStream outputStream = socket.getOutputStream();
outputStream.write("我已经接收完毕,你可以断开连接".getBytes());
fileOutputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}
4.2 Tomcat
服务端:
- 自定义 S
- Tomcat服务器 S:java后台开发!
客户端:
4.3 UDP
- 类 DatagramPacket:此类表示数据报包。
- 类 DatagramSocket:此类表示用来发送和接收数据报包的套接字。
实现发短信:不用连接,需要知道IP地址。 发送端:
public class UdpSendDemo {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
String msg="你好啊,服务器!";
InetAddress localhost = InetAddress.getByName("localhost");
int port=9090;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
socket.send(packet);
socket.close();
}
}
接收端:
public class UdpReceiveDemo {
public static void main(String[] args) throws Exception{
DatagramSocket socket = new DatagramSocket(9090);
byte[] buff =new byte[1024];
DatagramPacket packet = new DatagramPacket(buff, 0, buff.length);
socket.receive(packet);
System.out.println(packet.getAddress());
System.out.println(new String(packet.getData(),0,packet.getData().length));
socket.close();
}
}
实现控制台输入发信息: 发送方:
public class UdpSenderDemo2 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8888);
while (true) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String data = bufferedReader.readLine();
byte[] datas=data.getBytes();
DatagramPacket packet = new DatagramPacket(datas,0,data.length(),new InetSocketAddress("localhost",6666));
socket.send(packet);
if (data.equals("bye")){
break;
}
}
socket.close();
}
}
接收方:
public class UdpReceiverDemo2 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666);
while (true) {
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet);
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(receiveData);
if (receiveData.equals("bye")){
break;
}
}
socket.close();
}
}
线程实现相互发消息:
public class TalkSendDemo3 implements Runnable{
DatagramSocket socket =null;
BufferedReader bufferedReader = null;
private int fromPort;
private String toIP;
private int toPort;
public TalkSendDemo3(int fromPort, String toIP, int toPort) {
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;
try {
socket = new DatagramSocket(fromPort);
} catch (Exception e) {
e.printStackTrace();
}
bufferedReader =new BufferedReader(new InputStreamReader(System.in));
}
@Override
public void run() {
while (true) {
try {
String data = bufferedReader.readLine();
byte[] datas=data.getBytes();
DatagramPacket packet = new DatagramPacket(datas,0,data.length(),new InetSocketAddress(this.toIP,this.toPort));
socket.send(packet);
if (data.equals("bye")){
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
socket.close();
}
}
public class TalkReceiveDemo3 implements Runnable{
DatagramSocket socket = null;
private int port;
private String msgFrom;
public TalkReceiveDemo3(int port,String msgFrom) {
this.port = port;
this.msgFrom=msgFrom;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet);
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(msgFrom+":"+ receiveData);
if (receiveData.equals("bye")){
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
socket.close();
}
}
public class TalkStudentDemo3 {
public static void main(String[] args) {
new Thread(new TalkSendDemo3(7777,"localhost",9999)).start();
new Thread(new TalkReceiveDemo3(8888,"老师")).start();
}
}
public class TalkTeacherDemo3 {
public static void main(String[] args) {
new Thread(new TalkSendDemo3(5555,"localhost",8888)).start();
new Thread(new TalkReceiveDemo3(9999,"学生")).start();
}
}
5. URL
??统一资源定位符(URL):负责标识万维网上的各种文档,并使每个文档在整个万维网的范围内具有唯一的标识符URL。 URL一般形式: ??<协议>://<主机>:<端口>/<路径> <协议>指用什么协议获取万维网文档,常见有http、ftp等;<主机>表示存放资源的主机在因特网中的域名或者IP地址;<端口>和<路径>有时可省略。
URL获取信息:
在这里插入代码片public class TestInetSocketAddress {
public static void main(String[] args) {
InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8080);
InetSocketAddress socketAddress1 = new InetSocketAddress("localhost", 8080);
System.out.println(socketAddress);
System.out.println(socketAddress1);
System.out.println("====================");
System.out.println(socketAddress.getAddress());
System.out.println(socketAddress.getHostName());
System.out.println(socketAddress.getHostString());
System.out.println(socketAddress.getPort());
}
}
/127.0.0.1:8080
localhost/127.0.0.1:8080
====================
/127.0.0.1
127.0.0.1
127.0.0.1
8080
URL下载网页音乐资源:
public class URLDown {
public static void main(String[] args) throws IOException {
URL url = new URL("https://m10.music.126.net/20211124111116/0fd01ef9c0ad75c1cf74595991e9df1a/yyaac/obj/wonDkMOGw6XDiTHCmMOi/2234477133/c115/a4ab/23be/3eb3613b349ae1576b6e7206edcbd01e.m4a");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("晚风.m4a");
byte[] buffer = new byte[1024];
int len;
while ((len=inputStream.read(buffer))!=-1){
fileOutputStream.write(buffer,0,len);
}
}
}
完结撒花!
|