JavaWeb:网页编程,B / S
网络编程:TCP / IP, C / S
实现通信的要素:
双方地址:ip地址、端口号
规则:网络通信的协议 (TCP / IP 四层、 OSI 七层) 传输层:TCP,UDP
IP 地址:InetAddress、InetSocketAddress
IPV4 :127.0.0.1 本机 localhost,4个字节组成,0~255,42亿,2011年用尽
IPV6 :fe80::5c2b:59ca:7e10:1aae%8,128位,8个无符号整数,32个字节
公网 (互联网) 私网 (局域网)
InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1"); System.out.println(inetAddress1); // /127.0.0.1 InetAddress inetAddress2 = InetAddress.getByName("localhost"); System.out.println(inetAddress2); // localhost/127.0.0.1 InetAddress inetAddress3 = InetAddress.getLocalHost(); System.out.println(inetAddress3); // LAPTOP-VD0VHV6J/172.28.143.38
端口表示计算机上的一个程序的进程,TCP 端口从 0 ~ 65535,UDP 端口从 0 ~ 65535
单个协议下,端口不能冲突
公有端口 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 "80" # 查看指定的端口 tasklist|findstr "2376" # 查看指定端口的进程
速率、传输速率、代码结构、传输控制 . . .
TCP :用户传输协议,三次握手,四次挥手,客户端和服务端
UDP:用户数据报协议,DDOS 洪水攻击(饱和攻击)
// Client 连接服务器,发送消息 public class TcpClient { public static void main(String[] args) throws IOException { try { Socket socket = new Socket(InetAddress.getLocalHost(), 9999); OutputStream os = socket.getOutputStream(); os.write("你好,世界!".getBytes()); os.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } } } // Server 建立服务端口,等待用户连接,接收用户消息 public class TcpServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(9999); while (true) { Socket socket = serverSocket.accept(); InputStream inputStream = socket.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int length; while ((length = inputStream.read(data)) != -1) { // String s = new String(data, 0, length); // System.out.println(s); bos.write(data, 0, length); System.out.println(bos); } inputStream.close(); socket.close(); } } catch (IOException e) { e.printStackTrace(); } finally { if (serverSocket != null) { serverSocket.close(); } } } }
还有TCP文件上传
DatagramSocket、DatagramPacket
// 一端建立socket,建立包,发送包 public class UdpClient { public static void main(String[] args) throws Exception { // 建立一个socket DatagramSocket socket = new DatagramSocket(); // 建立一个包 String msg = "你好哇!世界!"; DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, InetAddress.getLocalHost(), 9090); // 发送一个包 socket.send(packet); // 关闭流 socket.close(); } } // 另一端建立socket,建立包,接收包 public class UdpServer { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(9090); byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length); socket.receive(packet); System.out.println(new String(buffer)); System.out.println(new String(packet.getData())); socket.close(); } }
URL组成: 协议 :// ip地址:端口 / 项目名 / 资源
定义一个URL,利用 url.openConnection().getInputStream()获取资源,最后connection.disconnect()断开连接