网络编程
目的:数据交换,通信
定位网络上的一台主机(端口)
javaweb:网络编程 B/S
网络编程:TCP/IP C/S
如何实现网络的通信?
通信双方的地址:ip,端口号
规则:网络通信的协议 http,ftp,tcp,udp…
IP
ip地址: InetAddress
-
唯一定义一台网络上的计算机
-
127.0.0.1:本机 localhost
-
ip地址的分类
- ip地址分类 ipv4/ipv6
- ipv4:127.0.0.1 四个字节组成 0-255 42亿个
- ipv6: 128位 8个无符号整数
- 公网(互联网)- 私网(局域网)
- 192.168.xxxx 专门给组织内部使用的
- ABCD类地址
- ip地址分类 ipv4/ipv6
-
域名:记忆ip问题
- ip:www.vip.com
package net.internet;
import java.net.InetAddress;
import java.net.UnknownHostException;
// test ip
public class Demo00 {
public static void main(String[] args) {
try {
// look localhost
InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
System.out.println(inetAddress1);
InetAddress inetAddress3 = InetAddress.getByName("localhost");
System.out.println(inetAddress3);
InetAddress inetAddress4 = InetAddress.getLocalHost();
System.out.println(inetAddress4);
// look up webset ip address
InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress2);
// methods
System.out.println(inetAddress2.getAddress());
System.out.println(inetAddress2.getCanonicalHostName());
System.out.println(inetAddress2.getHostAddress());
System.out.println(inetAddress2.getHostName());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
端口
表示计算机上的一个程序的进程
-
不同的进程有不同的端口号,用来区分软件
-
被规定 0 - 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 "5900" # 查看指定的端口 tasklist|findstr "8696" # 查看指定端口的进程 ctrl+shift+esc # 任务管理器
-
package net.internet;
import java.net.InetSocketAddress;
public class TestInetSocketAddress {
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()); // Address
System.out.println(socketAddress.getPort());
}
}
通信协议
网络通信协议:速率,传输码率,代码结构,传输控制…
TCP/IP协议簇:是一组协议
- TCP:用户传输协议
- UDP:用户数据报协议
- IP:网络互连协议
TCP UDP对比
TCP: 打电话
-
连接,稳定
-
三次握手,四次挥手
// 连接 最少需要三次,保证稳定连接 A: 你瞅啥 // 发送请求 B: 瞅你咋地 // 回应 A: 干一场 // 接受并回应 // 断开 A: 我们分手吧 B: 你真的要走吗? B: 你真的真的要走了吗? A: 我真的要走了
-
客户端,服务端
-
传输完成,释放连接,效率低
UDP: 发短信
- 不连接,不稳定
- 客户端、服务端:没有明确的界限
- 不管有没有准备好,都可以发给你
- 导弹
- DDOS:洪水攻击,饱和攻击,端口堵塞
TCP
客户端与服务器的消息传输
先启动服务器端,再启动客户端
客户端
- 通过 socket 连接服务器
- 发送消息
package net.internet;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
// client
public class TCPClientTest {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
try {
// 1. should know server's address
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
// 2. port
int port = 9999;
// 3. create a socket connection
socket = new Socket(serverIP,port);
// 4. send message I/O stream
os = socket.getOutputStream();
os.write("welcome to Java".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();
}
}
}
}
}
服务器
- 建立服务的端口 ServerSocket
- 等待用户的连接 accept
- 接收用户的消息
package net.internet;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServerTest {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
// 1. should have an address
serverSocket = new ServerSocket(9999);
while(true){
// 2. wait for connecting client
socket = serverSocket.accept();
// 3. read message of client
is = socket.getInputStream();
// pipe stream
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());
// this way avoids truncating and garbled
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// close resource
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();
}
}
}
}
}
文件上传
两者通过 socket 进行连接
客户端
package net.internet;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TestClientFileSender {
public static void main(String[]args) throws Exception{
// 1. create socket connection
Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9000);
// 2. create a output stream
OutputStream os = socket.getOutputStream();
// 3. read file; file stream: file-fileinputstream
FileInputStream fis = new FileInputStream(new File("/Users/pz/Desktop/study/javacode/javase/baseknown/src/net/internet/img1.jpg"));
// 4. write data to file
byte[] buffer = new byte[1024];
int len;
while((len=fis.read(buffer))!=-1){
os.write(buffer,0,len);
}
// notify server that client has done
socket.shutdownOutput(); // finished transferring
// make sure the server has finished connecting before disconnecting
InputStream inputStream = socket.getInputStream();
// String byte[]
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2;
while((len2=inputStream.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
// 5. close
baos.close();
inputStream.close();
fis.close();
os.close();
socket.close();
}
}
服务器
package net.internet;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServerFileSender {
public static void main(String[] args) throws Exception {
// 1. create server
ServerSocket serverSocket = new ServerSocket(9000);
// 2. listen client connection
Socket socket = serverSocket.accept();// block listener. Keep waiting client connection
// 3. get input stream
InputStream is = socket.getInputStream();
// 4. output file
FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));
byte[] buffer = new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
// Notify the client that the reception is complete
OutputStream os = socket.getOutputStream();
os.write("I received, you can disconnect".getBytes());
// 5. close
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}