Java网络编程

网络编程

  • 网络编程中有两个主要的问题
    • 如何准确的定位到网络上的一台或多台主机
    • 找到主机后如何通信
  • 网络编程中的要素
    • IP和端口号
    • 网络通信协议 udp tcp
  • 万物皆对象

IP

  • ip地址:InetAddress
    • 唯一定位一台网络上的计算机
    • 127.0.0.1:本机 localhost
    • ip地址的分类
    • IPV4/IPV6
    • 公网:(互联网)私网:(局域网)
  • InetSockedAddress
public class Demo1 {
    public static void main(String[] args) {
        try {
            //查询本机地址
            InetAddress ad1 = InetAddress.getByName("127.0.0.1");
            InetAddress ad11 = InetAddress.getByName("localhost");
            InetAddress ad12 = InetAddress.getLocalHost();
            System.out.println(ad11);
            System.out.println(ad12);
            //查询网站IP地址
            InetAddress ad2 = InetAddress.getByName("www.baidu.com");
            System.out.println(ad2);

            System.out.println(ad2.getHostAddress());
            System.out.println(ad2.getHostName());

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

端口

  • 端口表示计算机上的一个程序的进程
    • 不同的进程有不同的端口号
    • 被规定0-65535
  • 端口的分类
    • 公有端口0-1023
    • Http:80
    • Https:443
    • Ftp:21
    • Telnet:23
    • SSH远程连接:22
    • 程序注册端口:1024-49151,分配给用户或者程序
    • Tomcat:8080
    • MySql:3306
    • Oracle:1521
    • 动态,私有:49152-65535

通信协议

  • 协议:约定,就好比我们说的普通话
  • 网络通信协议:速率,传输码率,代码结构,传输控制…
  • TCP/IP协议簇,实际上是一组协议
    • 重要:
    • TCP:用户传输协议
    • UDP:用户数据报协议
  • TCP的三次握手和四次挥手
// 服务器
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);
            while (true){
                // 2.等待客户端连接  循环监听
                socket = serverSocket.accept();  // accept(); 监听
                // 3.读取客户端的消息
                is = socket.getInputStream();
                // 管道流
                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();
                }
            }
        }

    }
}
// 客户端
public class TcpClient {
    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.发送消息,相当于往外写
            os = socket.getOutputStream();
            String string = "我在学习网络编程...";
            os.write(string.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();
                }
            }
        }
    }
}

TCP 文件传输

public class FileServer {
    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("yang.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();
    }
}
	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("d:\\yy.jfif");
        byte[] buffer = new byte[1024];
        int len;
        while ((len=fis.read(buffer))!=-1){
            os.write(buffer,0,len);
        }

        //通知服务器,我已经结束
        socket.shutdownOutput();//我已经传输完了
        //确定服务器接受完毕,才能断开连接
        InputStream is = socket.getInputStream();
        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(new String(buffer2));

        baos.close();
        is.close();
        fis.close();
        os.close();
        socket.close();
    }
}

UDP

发送

public class Uclient {
    public static void main(String[] args) throws Exception {
        //1.建立一个socket
        DatagramSocket socket = new DatagramSocket();
        //2.建立包
        String s = "hello world";
        //数据,数据起始位置,数据结束位置,发送给谁,端口号
        DatagramPacket dp = new DatagramPacket(s.getBytes(),0,s.getBytes().length, InetAddress.getByName("localhost"),9090);
        //3.发送包
        socket.send(dp);
        socket.close();
    }
}

接收

public class Userver {
    public static void main(String[] args) throws Exception {
        //开放端口
        DatagramSocket datagramSocket = new DatagramSocket(9090);
        byte[] buffer = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);
        datagramSocket.receive(datagramPacket);
        System.out.println(datagramPacket.getAddress().getHostAddress());
        System.out.println(new String(datagramPacket.getData()));
        datagramSocket.close();
    }
}

UDP聊天实现

发送

public class Send {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8888);
        while (true){
            //准备数据:控制台读取,System.in
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            byte[] datas = reader.readLine().getBytes();
            DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));
            socket.send(packet);
            if (datas.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

接收

public class Recieve {
    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);
            //断开连接
            byte[] data = packet.getData();
            String s = new String(data, 0, data.length);
            System.out.println(s);
            if (s.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

UDP多线程在线咨询

public class TalkSend implements Runnable {
    DatagramSocket socket = null;
    BufferedReader reader = null;
    private String toIP;
    private int toPort;
    private int fromPort;

    public TalkSend(int fromPort, String toIP, int toPort ) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;

        try {
            socket = new DatagramSocket(fromPort);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        reader = new BufferedReader(new InputStreamReader(System.in));
    }

    @Override
    public void run() {
        while (true){
            //准备数据:控制台读取,System.in
            try {
                byte[] datas = new byte[1024];
                datas = reader.readLine().getBytes();
                DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));
                socket.send(packet);
                if (datas.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
public class TalkReceive implements Runnable {
    DatagramSocket socket = null;
    private int Port;

    public TalkReceive(int Port ) {
        this.Port = Port;

        try {
            socket = new DatagramSocket(Port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            //准备数据:控制台读取,System.in

            try {
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container,0,container.length);
                socket.receive(packet);
                byte[] data = packet.getData();
                String receiveData = new String(data, 0, data.length);
                System.out.println("收到来自端口"+packet.getPort()+":"+receiveData);
                if (receiveData.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
public class TalkStudent {
    public static void main(String[] args) {
        //开启两个线程
        new Thread(new TalkSend(7777,"localhost",9999),"student").start();
        new Thread(new TalkReceive(8888),"student").start();
    }
}
public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkSend(5555,"localhost",8888),"teacher").start();
        new Thread(new TalkReceive(9999),"teacher").start();
    }
}

URL下载网络资源

  • 统一资源定位符:定义互联网上的某一资源
public class Url {
    public static void main(String[] args) throws Exception{
        URL url = new URL("");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream("");
        byte[] buffer = new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        fos.close();
        urlConnection.disconnect();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值