网络编程Day02
通信协议
网络通信协议:速率、传输码率、代码结构、传输控制...
问题:非常的复杂
分层:大事化小
TCP/IP协议簇:实际上是一组协议
- TCP:用户传输协议
 - UDP:用户数据报协议
 - IP:网络互联协议
 
TCP UDP对比
- 
TCP:打电话
- 
连接,稳定
 - 
三次握手,四次分手
最少需要三次,保证稳定连接
最少需要四次,保证连接断开
 - 
客户端、服务端
 - 
传输完成,释放连接,效率低
 
 - 
 - 
UDP:发短信
- 不连接,不稳定
 - 客户端、服务端没有明确的界限
 - 不管有没有准备好,都可以发送
 
 
TCP
客户端
- 连接服务器Socket
 - 发送消息
 
package com.dongfang.ip.lesson02;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
//客户端
public class TCPClientDemo01 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.要知道服务器的地址,端口号
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            //2.创建一个socket连接
            socket = new Socket(serverIP,port);
            //3.发送消息IO流
            os = socket.getOutputStream();
            os.write("你好".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (os != null) {
                try{
                    os.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try{
                    socket.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
服务器
- 建立服务器端口ServerSocket
 - 等待用户的连接accept
 - 接收用户的消息
 
package com.dongfang.ip.lesson02;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务端
public class TCPServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //1.得有一个地址
            serverSocket = new ServerSocket(9999);
            //2.等待客户端连接过来
            socket = serverSocket.accept();//同一个socket
            //3.读取客户端的消息
            is = socket.getInputStream();
            /*
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1){
                String msg = new String(buffer, 0, len);
                System.out.println(msg);
            }
            */
            //管道流
            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();
                }
            }
        }
    }
}
文件上传
客户端
package com.dongfang.ip.lesson02;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TCPClientDemo02 {
    public static void main(String[] args) throws Exception {
        //1.创建一个Socket连接
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
        //2.创建一个输出流
        OutputStream os = socket.getOutputStream();
        //3.读取文件
        FileInputStream fis = new FileInputStream(new File("food_big.jpg"));
        //4.写出文件
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            os.write(buffer,0,len);
        }
        //通知服务器已经传输完毕
        socket.shutdownOutput();
        //确定服务器接收完毕才能够断开连接
        InputStream is = socket.getInputStream();
        //String byte[]
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer2 = new byte[1024];
        int len2;
        while ((len2 = is.read(buffer2)) != -1) {
            baos.write(buffer2,0,len2);
        }
        System.out.println(baos.toString());
        //5.关闭资源
        baos.close();
        fis.close();
        os.close();
        is.close();
        socket.close();
    }
}
服务器端
package com.dongfang.ip.lesson02;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServerDemo02 {
    public static void main(String[] args) throws Exception {
        //1.创建服务
        ServerSocket serverSocket = new ServerSocket(9000);
        //2.监听客户端的连接
        Socket socket = serverSocket.accept();//阻塞式监听,会一直等待客户端连接
        //3.获取输入流
        InputStream is = socket.getInputStream();
        //4.文件输出
        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);
        }
        //通知客户端接收完毕了
        OutputStream os = socket.getOutputStream();
        os.write("已接收完毕".getBytes());
        //5.关闭资源
        fos.close();
        is.close();
        serverSocket.close();
        socket.close();
    }
}
Tomcat
服务端
- 自定义 S
 - Tomcat服务器 S :Java后台开发
 
客户端
- 自定义 C
 - 浏览器 B
 
UDP
不用连接,但是需要知道对方的地址
发送端
package com.dongfang.ip.lesson03;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
//不需要连接服务器
public class UDPClientDemo01 {
    public static void main(String[] args) throws Exception {
        //1.建立一个Socket
        DatagramSocket socket = new DatagramSocket();
        //2.建个包
        String msg = "Hello World";
        //发送给谁
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;
        //数据  数据的起始长度  要发送给谁
        DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
        //3.发送包
        socket.send(packet);
        //4.关闭流
        socket.close();
    }
}
接收端
package com.dongfang.ip.lesson03;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
//还是要等待客户端的连接
public class UDPServerDemo01 {
    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(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));
        //关闭连接
        socket.close();
    }
}
UDP聊天
循环发送消息
package com.dongfang.ip.chat;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class UDPSenderDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8888);
        //准备数据:控制台读取System.in
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String data = reader.readLine();
        byte[] datas = data.getBytes();
        DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));
        socket.send(packet);
        socket.close();
    }
}
循环接收消息
import java.net.DatagramSocket;
public class UDPReceiveDemo01 {
    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);//阻塞式接收包
            //断开连接  bye
            byte[] data = packet.getData();
            String receiveData = new String(data, 0, packet.getLength());
            System.out.println(receiveData);
            if (receiveData.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}
两个人都可以是发送方和接收方
URL
统一资源定位符:定位互联网上的某一个资源
协议://ip地址:端口/项目名/资源
package com.dongfang.ip.lesson04;
import java.net.MalformedURLException;
import java.net.URL;
public class URLDemo01 {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=dongfangyulv&password=123");
        
        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.dongfang.ip.lesson04;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLDown {
    public static void main(String[] args) throws Exception{
        //1.下载地址
        URL url = new URL("http://localhost:8080/dongfangyulv/SecurityFile.txt");
        //连接到这个资源  HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream("SecurityFile.txt");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != 1){
            fos.write(buffer,0,len);//写出这个数据
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();//断开连接
    }
}
                    
                
                
            
        
浙公网安备 33010602011771号