网络编程–TCP、UDP

1.1、网络通信要素

1.网络编程中两个主要问题

  • 如何准确定位到网络上的一台主机或者多台主机

  • 找到主机之后如何进行通信

2.网络编程中的要素

  • IP和端口号

  • 网络通信协议 UDP、TCP

1.2、IP

ip地址:InetAdsress

  • 唯一定位一台网络上计算机

  • 127.0.0.1:本机localhost

  • ip地址的分类

    • ipv4 / ipv6
      • ipv4 127.0.0.1 四个字节组成,0-255,
      • ipv6
    • 公网(互联网)-私网(局域网)
import java.net.InetAddress;
import java.net.UnknownHostException;

//测试IP
public class TestInetAddress {
    public static void main(String[] args) throws UnknownHostException {
        InetAddress inetAddress =InetAddress.getByName("127.0.0.1");
        System.out.println(inetAddress);

        InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com");
        System.out.println(inetAddress2);

        //常用方法
        System.out.println(inetAddress2.getAddress());
        System.out.println(inetAddress2.getCanonicalHostName());
        System.out.println(inetAddress2.getHostAddress());
    }
}

1.3、端口

端口表示一个程序的进程;

  • 不同的进程有不同的端口号

  • 被规定为0-65535

  • 端口分类

    • 公有端口0-1023

      • http:80
      • https:443
      • ftp:21
      • telnet:23
    • 程序注册端口:10124-49151,分配用户或者程序

      • Tomcat:8080
      • MySQL:3306
      • Oracle:1521
    • 动态,私有:49152-65535

#查看所有端口
netstat -ano 
# 查看指定2392端口的进程
netstat -ano|findstr "2392" 
Ctrl+shift+ESC

1.4、通信协议

协议:约定

网络通信协议:速率、传输码率、代码结构、传输控制。。

TCP/IP协议簇:实际上是一组协议

TCP:用户传输协议

UDP:用户数据报协议

IP:网络互联协议

TCP-UDP对比

TCP :

  • 连接、稳定
  • 三次握手四次挥手
  • 客户端、服务端
  • 传输完成、释放连接、效率低

UDP:

  • 不连接,不稳定
  • 客户端、服务端:没有明确的界限
  • 不管有没有准备好都可以发给你

1.5、TCP

客户端

1.连接服务器Socket

2.发送消息

public class TcpClient {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.要知道服务器地址
            InetAddress serverIp = getByName("127.0.0.1");
            int port = 9999;
            //2.创建一个socket链接
            socket = new Socket(serverIp,port);
            //3.发送消息 io流
            os = socket.getOutputStream();
            os.write("hello".getBytes());

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

服务器

1.建立服务器的端口 ServerSocket

2.等待用户的连接 accept()

3.接受用户的消息

public class TcpServer {
    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();
            //3.读取客户端消息
            is = socket.getInputStream();
            //管道流
            baos = new ByteArrayOutputStream();
            byte [] buffer = new byte[1024];
            int len;
            while((len=is.read())!=-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();
               }
           }

        }

    }
}
文件上传

客户端:

public class TcpClient2 {
    public static void main(String[] args) throws IOException {
        //1.创建一个Socket连接
        Socket socket;
        socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
        //2.创建一个输出流
        OutputStream os = socket.getOutputStream();
        //3.读文件
        FileInputStream fis = new FileInputStream("1.png");
        //4.写文件
        byte []buffer = new byte[1024];
        int len;
        while((len=fis.read())!=-1){
            os.write(buffer,0,len);
        }

        //5.关闭资源
        if (fis!=null){
            fis.close();
        }
        if (socket!=null){
            socket.close();
        }

    }
}

服务端:

public class TcpServer2 {
    public static void main(String[] args) throws IOException {
        //1.创建服务
        ServerSocket serverSocket = new ServerSocket(9999);
        //2.监听客户端的连接
        Socket socket = serverSocket.accept();//阻塞式监听,会一直等待客户端连接
        //3.获取输入流
        InputStream is = socket.getInputStream();
        //4.文件输出
        FileOutputStream fos= new FileOutputStream(new File("so1.png"));
        byte []buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1) {
            fos.write(buffer,0,len);
        }
        //5.关闭资源
        if (fos!=null){
            fos.close();
        }
        if (is!=null){
            is.close();
        }
        if (socket!=null){
            socket.close();
        }
        if (serverSocket!=null){
            serverSocket.close();
        }
    }
}
Tomcat

服务端:

  • 自定义S:
  • Tomcat 服务器S:java后台开发

客户端:

  • 自定义C
  • 浏览器B

1.6、UDP

UDP发送消息

发送端:

import java.io.IOException;
import java.net.*;

//不需要连接服务器
public class UdpClient {
    public static void main(String[] args) throws IOException {
        //1.建立一个socket
        DatagramSocket socket = new DatagramSocket();
        //2.建立包
        String msg = "你好呀,服务器!";
        //发送给谁
        InetAddress localhost = InetAddress.getByName("localhost");
        int port= 9999;
        //数据,数据的长度起始
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
        //3.发送包
        socket.send(packet);
        //4.关闭
        socket.close();
    }
}

接收端:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpServer {
    public static void main(String[] args) throws IOException {
        //开放端口
        DatagramSocket socket = new DatagramSocket(9999);
        //接受数据包
        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聊天

发送端:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

public class UdpSender {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8888);

        //准备数据
        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",999));

        socket.send(packet);
        socket.close();

    }
}

接收端:

import org.omg.CORBA.DATA_CONVERSION;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpReceiver {
    public static void main(String[] args) throws IOException {

        DatagramSocket socket = new DatagramSocket(9999);

        while (true){
            //准备接收包裹
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container,0,container.length);
            socket.receive(packet); //阻塞式接收包裹

            //断开连接 bye
            byte [] data =  packet.getData();
            String recreiveData = new String(data,0,data.length);
            System.out.println(recreiveData);
            if (recreiveData.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值