网络编程概述
计算机网络:
计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现[源共享和信息传递的计算机系统。
网络编程的目的:
传播交流信息、数据交换、通信等
想要达到的效果需要什么:
- 如何准确地定位网络上的某一台主机,定位到这个计算机上的某个资源
- 找到了这台主机,该如何传递数据?
- javaweb:网页编程 B/S架构
- 网络编程:TCP/IP C/S架构
网络通信的要素
如何实现网络的通信?
可以通信双方地址:
规则:网络通信的协议
TCP/IP参考模型
IP
ip地址:InetAddress
- 唯一定位一台网络计算机
- 127.0.0.1:本机localhost
- ip地址的分类
- IPV4/IPV6
- IPV4:127.0.0.1 4个字节组成 0~255 42亿(30亿都在北美,亚洲四亿,在2011年已被用尽)
- IPV6:128位 8个无符号整数!
- 公网(互联网)/私网(局域网)
- 域名:记忆IP问题!
public class TestInetAddress {
public static void main(String[] args) throws UnknownHostException {
System.out.println(InetAddress.getByName("127.0.0.1"));
System.out.println(InetAddress.getByName("localhost"));
System.out.println(InetAddress.getLocalHost());
System.out.println(InetAddress.getByName("www.baidu.com"));
System.out.println(InetAddress.getByName("www.baidu.com").getAddress());
System.out.println(InetAddress.getByName("www.baidu.com").getCanonicalHostName());
System.out.println(InetAddress.getByName("www.baidu.com").getHostAddress());
System.out.println(InetAddress.getByName("www.baidu.com").getHostName());
}
}
端口
端口表示计算机上的一个程序的进程;
- 不同的进程有不同的端口号,且端口号不能重复!用于区分软件!
- 被规定为0~65535
- TCP、UDP:65535×2(假设TCP使用了80端口,UDP使用了80端口,这两者并不冲突,单个协议下面,端口号不能冲突)
- 端口分类
- 公有端口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 "5900"
tasklist|findstr "6420"
public class TestSocketAddress {
public static void main(String[] args) {
InetSocketAddress i1 = new InetSocketAddress("127.0.0.1", 6420);
System.out.println(i1);
InetSocketAddress i2 = new InetSocketAddress("localhost", 6420);
System.out.println(i2);
System.out.println(i1.getAddress());
System.out.println(i1.getHostName());
System.out.println(i1.getPort());
}
}
通信协议
**网络通信协议:**速率、传送码率、代码结构、传输控制…
TCP/IP协议簇
重要:
- TCP:用户传输协议
- 类似于打电话
- 链接稳定
- 三次握手、四次挥手
- 客户端、服务端
- 传输完成,释放连接,效率低
- UDP:用户数据报协议
- 不连接,不稳定
- 客户端、服务端:没有明确的界限
- 不管有没有准备好,都可以进行发送
- 导弹
- DDOS:洪水攻击!发送大量无用文件,造成端口堵塞!
三次握手、四次挥手
三次握手:
四次挥手:
出名的协议:
TCP实现消息传递
客户端:
- 建立连接
- 发送信息
public class TCPClientDemo {
public static void main(String[] args) throws Exception{
Socket socket = null;
OutputStream os = null;
try {
InetAddress serverIp = InetAddress.getByName("localhost");
int port = 9999;
socket = new Socket(serverIp,port);
os = socket.getOutputStream();
os.write("Hi~想我了吗?".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (os != null) {
os.close();
}
if (socket != null) {
socket.close();
}
}
}
}
服务端:
- 建立服务连接的端口 ServerSocket、
- 等待用户的连接 accept
- 接收用户信息
public class TCPServerDemo {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = null;
Socket accept = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
serverSocket = new ServerSocket(9999);
accept = serverSocket.accept();
is = accept.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = -1;
while ((len = is.read(buff)) != -1) {
baos.write(buff, 0, len);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (baos != null) {
baos.close();
}
if (is != null) {
is.close();
}
if (accept != null) {
accept.close();
}
if (serverSocket != null) {
serverSocket.close();
}
}
}
}
TCP实现文件上传
客户端:
public class TCPClientDemo02 {
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000 );
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File("zhongli.png"));
byte[] bytes = new byte[1024];
int len;
while((len = fis.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int len2;
while((len2 = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, len2);
}
System.out.println(baos.toString());
baos.close();
inputStream.close();
fis.close();
os.close();
socket.close();
}
}
服务端:
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9000);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("received.png"));
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
OutputStream os = socket.getOutputStream();
os.write("我已接收完毕!".getBytes());
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
Tomcat
服务端:
- 自定义 S
- Tomcat服务器 S:Java后台开发
客户端:
UDP
类似于日常生活中的发短信,并不需要链接,但需要知道对方的地址!虽说不需要链接,但是仍然需要一个接收端,就好比收快递,快递员可以根据地址将快递送达,并不需要去等你去确认之后再把快递送过去,但还是需要有人去把快递签收。
发送端:
public class UDPClientDemo {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
String msg = "你好啊,Ayin";
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 UDPServerDemo {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9090);
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
socket.receive(packet);
System.out.println(packet.getAddress().getHostName());
System.out.println(new String(packet.getData(), 0, packet.getLength()));
socket.close();
}
}
UDP实现单向聊天
需求:一方发送消息,一方接收消息
发送端:
public class UDPSenderDemo {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(8080);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while(true) {
String data = reader.readLine();
byte[] msg = data.getBytes();
DatagramPacket packet = new DatagramPacket(msg, 0, msg.length, new InetSocketAddress("localhost", 6666));
socket.send(packet);
if (data.equals("bye")) {
break;
}
}
socket.close();
}
}
接收端:
public class UDPReceiveDemo {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(6666);
while(true) {
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
socket.receive(packet);
byte[] msg = packet.getData();
String receiveData = new String(msg, 0, packet.getLength());
System.out.println(receiveData.trim());
if (receiveData.equals("bye")) {
break;
}
}
socket.close();
}
}
UDP实现双向聊天
需求:双方都可以接收消息,也可以发送消息。
发送端:
public class TalkSend implements Runnable {
DatagramSocket socket = null;
BufferedReader reader = null;
private int formIP;
private String toIP;
private int toPort;
public TalkSend(int formIP, String toIP, int toPort) {
this.formIP = formIP;
this.toIP = toIP;
this.toPort = toPort;
try {
socket = new DatagramSocket(formIP);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(true) {
try {
String data = reader.readLine();
byte[] msg = data.getBytes();
DatagramPacket packet = new DatagramPacket(msg, 0, msg.length, new InetSocketAddress(this.toIP, this.toPort));
socket.send(packet);
if (data.equals("bye")) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
接收端:
public class TalkReceive implements Runnable{
DatagramSocket socket = null;
private int Port;
private String name;
public TalkReceive(int port, String name) {
this.Port = port;
this.name = name;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(true) {
try {
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
socket.receive(packet);
byte[] msg = packet.getData();
String receiveData = new String(msg, 0, packet.getLength());
System.out.println("收到来自" + name + "的消息: " + receiveData);
if (receiveData.equals("bye")) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
测试类:
public class TalkUser01 {
public static void main(String[] args) {
new Thread(new TalkSend(9999, "localhost", 8888)).start();
new Thread(new TalkReceive(7777, "User2")).start();
}
}
public class TalkUser02 {
public static void main(String[] args) {
new Thread(new TalkSend(6666, "localhost", 7777)).start();
new Thread(new TalkReceive(8888, "User1")).start();
}
}
URL
https://www.baidu.com
统一资源定位符:定位资源的,定位互联网的某一个资源
DNS域名解析:
协议:ip地址:端口/项目名/资源
使用URL下载网络文件
public class URLDowm {
public static void main(String[] args) throws IOException {
URL url = new URL("#");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("picture.png");
byte[] bytes = new byte[1024];
int len;
while((len = is.read(bytes)) != -1){
fos.write(bytes, 0, len);
}
fos.close();
is.close();
urlConnection.disconnect();
}
}
|