Java网络编程
初始
计算机网络:
计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统
网络编程的目的:
无线电台…传播交流信息,数据交换。通信
想要达到这个效果需要什么:
- 如何准确的定位网络上的一台主机 192.168.16.124:端口,定位到这个计算机上的某个资源
- 找到了这个主机,如何传输数据呢?
网络通信的要素
如何实现网络的通信:
通信双方的地址:ip:端口
规则:网络通信协议:TCP/IP
Ip
IP地址:InetAddress
- 唯一,
- 127.0.0.1:本机(localhost),
- 分类:
- IPV4/IPV6(ipv4,4个字节组成)(ipv6,128位,8个无符号整数)
- 公网(互联网)和私网(局域网),了解(ABCD类地址)
端口
端口表示计算机上的一个程序的进程;
-
不同的进程有不同的端口号,用来区分软件
-
被规定1–65535
-
TCP,UDP:65535*2 单个协议下,端口号不能冲突
-
端口分类
-
共有端口:0-1023
-
http:80
-
https:443
-
FTP:21
-
Telent:23
-
-
程序注册端口:1024-49151,分配用户或程序
- Tomcat:8080
- Mysql:3306
- Oracle:1521
-
动态、私有:49152–65535
-
netstat -ano #查看所有端口
netstat -ano|findstr "5990" #查看指定的端口
tasklist|finstr "8696" #查看指定端口的进程
Ctrl+shift+esc
package com.classip;
import java.net.InetSocketAddress;
public class InserSocket {
public static void main(String[] args) {
InetSocketAddress socketAddress=new InetSocketAddress("127.0.0.1",8080);
System.out.println(socketAddress);
System.out.println(socketAddress.getAddress());
System.out.println(socketAddress.getHostName());
System.out.println(socketAddress.getPort());
}
}
通信协议
网络通信协议:速率,传输麻率、代码结构、传输控制……
TCP/IP协议簇:实际是一组协议
重要:
- TCP:用户传输协议
- IP:用户数据报协议
TCP UDP对比
tcp:打电话
-
链接,稳定
-
三次握手,四次挥手
-
最少需要删除,保证稳定链接
-
你瞅啥?
-
瞅你咋地?
-
干一场
-
我要走了
-
我真的要走了
-
你真的真的要走了吗
-
我要走了
-
- 客户端,服务端
- 传输完成,释放链接,效率低
udp:发短信
- 不连接,不稳定
- 客户端,服务端,没有明确的界限
- 不管有没有准备好,都可以发给你
- DDOS:洪水攻击(饱和攻击)
TCP
客户端:
-
连接服务器Socket
-
发送消息
package com.ClassIp2; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; //客户端 public class TcpClicentDome1 { public static void main(String[] args) { Socket socket=null; OutputStream stream=null; try { //要知道服务器地址 InetAddress byName = InetAddress.getByName("127.0.0.1"); //端口号 int port=9999; //创建socket链接 socket=new Socket(byName,port); //发送IO流信息 stream=socket.getOutputStream(); stream.write("你好呀".getBytes()); } catch (Exception e) { e.printStackTrace(); }finally { //关闭流 if (stream != null){ try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket!=null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
服务端:
-
建立服务的端口SercerSocket
-
等待用户的连接accept
-
接收用户的消息
package com.ClassIp2; import com.sun.security.ntlm.Server; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; //服务端 public class TcpServiceDome1 { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; InputStream is = null; ByteArrayOutputStream bose = null; //我有一个地址 try { serverSocket = new ServerSocket(9999); while (true){ //等待客户端谅解 socket = serverSocket.accept(); //读取客户端的消息 is = socket.getInputStream(); //管道流 bose = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { bose.write(buffer, 0, len); } System.out.println(bose.toString()); } } catch (Exception e) { e.printStackTrace(); } finally { //关闭流 if (bose != null) { try { bose.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(); } } } } }
文件上传
客户端上传
package com.ClassIp2;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClientDome2 {
//文件上传客户端
public static void main(String[] args) throws Exception {
//创建一个socket连接
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
//创建一个输出流
OutputStream outputStream = socket.getOutputStream();
//文件流
FileInputStream fileInputStream = new FileInputStream(new File("network/untitled.png"));
//写出文件
byte[] buffer = new byte[2024];
int len;
while ((len = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
//通知服务器我已经结束了,你可以开始接受文件了
socket.shutdownOutput();//我已经传输完了
//确定服务器接收完毕才能断开连接
InputStream inputStream = socket.getInputStream();
//String byte[]
//管道流--接收消息
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[2024];
int len2;
while ((len2=inputStream.read(bytes))!=-1){
byteArrayOutputStream.write(bytes,0,len2);
}
System.out.println(byteArrayOutputStream.toString());
//关闭流
byteArrayOutputStream.close();
inputStream.close();
fileInputStream.close();
outputStream.close();
socket.close();
}
}
服务端接收
package com.ClassIp2;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpSericeDome2 {
//文件上传服务端
public static void main(String[] args) throws Exception {
//创建服务和端口
ServerSocket serverSocket = new ServerSocket(9999);
//监听客户端连接
Socket accept = serverSocket.accept();//阻塞式监听,会一直等待客户端连接
//获取输入流
InputStream inputStream = accept.getInputStream();
//文件输出
FileOutputStream receive = new FileOutputStream(new File("receive.png"));
byte[] buffer = new byte[2024];
int len;
while ((len=inputStream.read(buffer))!=-1){
receive.write(buffer,0,len);
}
//通知客户端接收完毕
OutputStream outputStream = accept.getOutputStream();
outputStream.write("已接收完毕".getBytes());
//关闭流
receive.close();
inputStream.close();
accept.close();
serverSocket.close();
}
}
Tomcat
服务端
- 自定义 S
- Tomcat服务器 S JAVA后天开发
客户端
- 自定义 C
- 浏览器 B
UDP
类似发短信:不用连接,需要知道对方的地址!
发送消息
package com.ClassUdp;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpCllientDome {
//不需要连接服务器
public static void main(String[] args) throws Exception {
//建立一个Socket
DatagramSocket datagramSocket = new DatagramSocket();
//建一个包
String mes="你好呀服务器";
//发送给谁
InetAddress localhost = InetAddress.getByName("localhost");
int port=9090;
DatagramPacket datagramPacket = new DatagramPacket(mes.getBytes(), 0, mes.getBytes().length, localhost, port);
//发送一个包
datagramSocket.send(datagramPacket);
//关闭流
datagramSocket.close();
}
}
接收消息
package com.ClassUdp;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
//还是要等待客户端的连接
public class UdpServiceDome {
public static void main(String[] args) throws Exception {
//开发端口
DatagramSocket datagramSocket = new DatagramSocket(9090);
//接收数据包
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length);//接收
datagramSocket.receive(datagramPacket);
System.out.println(datagramPacket.getAddress().getHostAddress());
System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
//关闭连接
datagramSocket.close();
}
}
UDP构建聊天
单方面发送消息
package com.UdpChat;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetSocketAddress;public class UdpChatSender { //发送端 public static void main(String[] args) throws Exception { //创建一个socket DatagramSocket datagramSocket = new DatagramSocket(8888); //准备数据,读取控制台system in BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //持续聊天 while (true){ //接收控制台输入的数据 String date=reader.readLine(); //转为字节数组 byte[] dates=date.getBytes(); //数据入流 DatagramPacket packet = new DatagramPacket(dates, 0, dates.length,new InetSocketAddress("localhost",6666)); //发送流 datagramSocket.send(packet); //退出 if (date.equals("bye")){ break; } } //关闭流 datagramSocket.close(); }}
单方面接收消息
package com.UdpChat;import java.net.DatagramPacket;import java.net.DatagramSocket;public class UdpChatReceive { //接收端 public static void main(String[] args) throws Exception { //创建一个socket DatagramSocket datagramSocket = new DatagramSocket(6666); while (true){ //准备接收包 byte[] container = new byte[2048]; DatagramPacket datagramPacket = new DatagramPacket(container,0,container.length); //阻塞接收数据 datagramSocket.receive(datagramPacket); //断开连接 //获取数据变为字节数组 byte[] data = datagramPacket.getData(); //类型转换 String receiveDate = new String(data, 0, data.length); //显示数据 System.out.println(receiveDate); //退出循环 if (receiveDate.equals("bye")){ break; } } //关闭流 datagramSocket.close(); }}
*多线程互相发送与接收
封装两个线程
发送端
package com.TaskUDP;import javax.print.attribute.standard.NumberUp;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetSocketAddress;import java.net.SocketException;public class TaskSender implements Runnable { DatagramSocket datagramSocket = null; BufferedReader reader =null; private int formPort; private String toIP; private int toPort; public TaskSender(int formPort, String toIP, int toPort) { this.formPort = formPort; this.toIP = toIP; this.toPort = toPort; try { //创建一个socket datagramSocket = new DatagramSocket(formPort); //准备数据,读取控制台system in reader = new BufferedReader(new InputStreamReader(System.in)); } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { //持续聊天 while (true){ try { //接收控制台输入的数据 String date=reader.readLine(); //转为字节数组 byte[] dates=date.getBytes(); //数据入流 DatagramPacket packet = new DatagramPacket(dates, 0, dates.length,new InetSocketAddress(this.toIP,this.toPort)); //发送流 datagramSocket.send(packet); //退出 if (date.equals("bye")){ break; } } catch (Exception e) { e.printStackTrace(); } } //关闭流 datagramSocket.close(); }}
接收端
package com.TaskUDP;import java.net.DatagramPacket;import java.net.DatagramSocket;public class TaskReceive implements Runnable{ DatagramSocket datagramSocket =null; private int port; private String msgForm; public TaskReceive(int port,String msgForm) { this.port = port; this.msgForm=msgForm; try { //创建一个socket datagramSocket = new DatagramSocket(port); } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { while (true){ try { //准备接收包 byte[] container = new byte[2048]; DatagramPacket datagramPacket = new DatagramPacket(container,0,container.length); //阻塞接收数据 datagramSocket.receive(datagramPacket); //断开连接 //获取数据变为字节数组 byte[] data = datagramPacket.getData(); //类型转换 String receiveDate = new String(data, 0, data.length); //显示数据 System.out.println(msgForm+":"+receiveDate); //退出循环 if (receiveDate.equals("bye")){ break; } } catch (Exception e) { e.printStackTrace(); } } //关闭流 datagramSocket.close(); }}
实现
package com.TaskUDP;public class TaskStudent { public static void main(String[] args) { //开启两个线程 Thread sender = new Thread(new TaskSender(7777,"localhost",9999)); Thread Recevie = new Thread(new TaskReceive(8888,"老师")); //开启线程 sender.start(); Recevie.start(); }}
package com.TaskUDP;public class TaskTaecher { public static void main(String[] args) { //开启两个线程 Thread sender = new Thread(new TaskSender(5555,"localhost",8888)); Thread Recevie = new Thread(new TaskReceive(9999,"学生")); //开启线程 sender.start(); Recevie.start(); }}
URL下载
统一资源定位符:地位资源,定位互联网上的某个资源
DNS域名解析:www.baidu.com
协议://ip地址:端口号/项目名/资源
package com;import java.net.MalformedURLException;import java.net.URI;import java.net.URL;public class ClassUrlDome { public static void main(String[] args) throws MalformedURLException { URL url = new URL("http://www.cikxk.cn:86/CikBlog/Login.html?user='xk'&&pwd='123456'"); System.out.println(url.getProtocol());//协议 System.out.println(url.getHost());//主机IP System.out.println(url.getPort());//端口 System.out.println(url.getPath());//文件 System.out.println(url.getFile());//文件全路径 System.out.println(url.getQuery());//参数 }}
package com;import java.io.FileOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;public class UrlDown { public static void main(String[] args) throws Exception { //下载地址 URL url = new URL("http://abc.cikxk.cn:84/Home/Facility"); //连接到这个资源 HTTP HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //数据流 InputStream inputStream = urlConnection.getInputStream(); //文件流 FileOutputStream fileOutputStream = new FileOutputStream("Facility.cs"); byte[] bytes = new byte[5000]; int len; while ((len=inputStream.read(bytes))!=-1){ fileOutputStream.write(bytes,0,len);//写出这个数据 } //关闭流 fileOutputStream.close(); inputStream.close(); urlConnection.disconnect();//断开连接 }}