栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java网络编程实战

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java网络编程实战

一、什么是计算机网络

打电话--连接--接了--通话    TCP

发信息--发送就完事了--接收  UDP(可能会掉包)

javaweb:网页编程   B/S架构(浏览器)

网络编程:TCP/IP     C/S架构(客户端)

二、网络通信的两个要素 1.如何实现网络通信?

1.通信双方地址:ip   端口号

2.网络通信的协议:

三、IP地址

ip地址:InetAddress

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

127.0.0.1:本机 localhost

ip地址的分类:

1.ipv4/ipv6:ipv4  127.0.0.1,4个字节组成(每个字节长度0-255,十进制点隔开)

                    ipv6   2409:8a20:2c19:7b60:e1be:5973:c280:e399(十六进制)    128位(2的128次方个字节)   8个无符号整数

2.公网(互联网)-私网(局域网)

ABCD类地址

192.168.xx.xx 局域网 专门给组织内部使用

域名:记忆ip问题   IP:www.vip.com

package WangLuoBianCheng;

import java.net.InetAddress;
import java.net.UnknownHostException;

// 测试IP
public class TestInetAddress {
     public static void main(String[] args) {
         try {//查询本机地址
             InetAddress inetAddress3= InetAddress.getByName("localhost");
             System.out.println(inetAddress3);
             InetAddress inetAddress4= InetAddress.getLocalHost();
             System.out.println(inetAddress4);
             InetAddress inetAddress1= InetAddress.getByName("127.0.0.1");
             System.out.println(inetAddress1);
                     //查询网络ip地址
             InetAddress inetAddress2= InetAddress.getByName("www.baidu.com");
             System.out.println(inetAddress2);
         } catch (UnknownHostException e) {
             throw new RuntimeException(e);
         }
     }
}
四、端口Port

端口表示计算机上的一个程序的进程 :

不同的进程有不同的端口号!用来区分软件!

被规定为0-65535

包含有有TCP,UDP:总共65535*2        TCP为80,UDP也可以是80,但在单个协议下,端口号不能冲突

端口分类:

1.公有端口 0-1023(尽量不要占用) 例:HTTP:80    HTTPS:443    FTP(文件传输):21

Telent(远程控制):23

2.程序注册端口:1024-49151,分配用户或者程序

Tomcat:8080    MySQL:3306    Oracle:1521

3.动态、私有(也不要放在这里面):49152-65535

package cn.bloghut.lesson01;

import java.net.InetSocketAddress;

public class TesyInetSocketAddress {
    public static void main(String[] args) {

        InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8080);
        InetSocketAddress socketAddress1 = new InetSocketAddress("localhost", 8080);

        System.out.println(socketAddress);
        System.out.println(socketAddress1);
        System.out.println("====================");

        System.out.println(socketAddress.getAddress());//ip地址
        System.out.println(socketAddress.getHostName());//主机名称
        System.out.println(socketAddress.getHostString());
        System.out.println(socketAddress.getPort());//端口
        
    }
}
五、通信协议

网络通信协议:1.速率2.传输码率3.代码结构4.传输控制...

TCP/IP协议簇(实际上是一组协议)   重要的有:TCP:用户传输协议   UDP:用户数据报协议

出名的协议:TCP:用户传输协议    IP:网络互连协议

六、TCP实现聊天

客户端:1.建立连接    2.发送消息

package cn.bloghut.lesson02;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClientDemo1 {

    public static void main(String[] args) throws Exception{
        Socket socket = null;
        OutputStream os = null;
        //要知道服务器地址
        try {
            InetAddress serverIp = InetAddress.getByName("localhost");
            int port = 9999;
            //2.创建连接
            socket = new Socket(serverIp,port);
            //3.发生消息 IO流
            os = socket.getOutputStream();
            os.write("你好,闲言".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (os != null) {
                os.close();
            }
            if (socket != null) {
                socket.close();
            }

        }


    }
}

服务器:
    1.建立服务连接的端口 ServerSocket
  2.等待用户的连接 accept
  3.接收用户信息

package cn.bloghut.lesson02;

import java.io.ByteArrayInputStream;
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) throws Exception {
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //1. 我得有一个地址
            serverSocket = new ServerSocket(9999);
            //2.等待客户端连接过来
            accept = serverSocket.accept();
            //3.读取客户端消息
            is = accept.getInputStream();

        

            //管道流
            baos = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len = -1;

            while ((len = is.read(buff)) != -1) {
                baos.write(buff, 0, len);
            }
            System.out.println(baos.toString());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (baos != null) {
                baos.close();
            }
            if (is != null) {
                is.close();
            }
            if (accept != null) {
                accept.close();
            }
            if (serverSocket != null) {
                serverSocket.close();
            }
        }
    }


}
七、TCP文件上传实现

客户端

package cn.bloghut.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 TcpServerDemo2 {
    public static void main(String[] args)  throws Exception{
        //1.创建服务
        ServerSocket serverSocket = new ServerSocket(9999);
        //2.监听客户端连接
        Socket accept = serverSocket.accept();
        //3.获取输入流
        InputStream is = accept.getInputStream();

        //4.文件输出
        FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));//接收文件就要用文件的管道流
        byte[] buff = new byte[1024];
        int len;
        while ((len = is.read(buff)) != -1){
            fos.write(buff,0,len);
        }


        //通过客户端我接收完毕了
        OutputStream os = accept.getOutputStream();
        os.write("我接收完毕了,你可以断开了".getBytes());

        fos.close();
        is.close();
        accept.close();
        serverSocket.close();

    }
}

服务器端

package cn.bloghut.lesson02;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;


public class TcpClientDemo2 {

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

        //通知服务器,我已经结束了
        socket.shutdownOutput();//我已经传输完了的意思

        //确定服务器接收完毕,才能够断开连接
        InputStream inputStream = socket.getInputStream();//接收字符、就用字节的管道流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buff2 = new byte[1024];
        int len2;
        while ((len2 = inputStream.read(buff)) != -1) {
            bos.write(buff2, 0, len2);
        }
        System.out.println(bos.toString());


        //5.释放资源
        bos.close();
        inputStream.close();
        is.close();
        os.close();
        socket.close();

    }

}
八、UDP消息发送

发短信,需要IP地址

发送消息

package cn.bloghut.lesson3;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpClientDemo1 {
    public static void main(String[] args) throws Exception{

        //1.建立一个Socket
        DatagramSocket socket = new DatagramSocket();
        //2.建个包
        String msg = "你好啊,服务器";
        //3.发送给谁
        InetAddress address = InetAddress.getByName("localhost");
        int port = 9090;

        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, address, port);
        //4.发送包
        socket.send(packet);


    }
}

接收端

package cn.bloghut.lesson3;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;


public class UdpServerDemo1 {
    public static void main(String[] args) throws Exception{
        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);
        //接收数据包
        byte[] buff =new byte[1024];
        DatagramPacket packet = new DatagramPacket(buff, 0, buff.length);

        socket.receive(packet);//阻塞接收

        System.out.println(packet.getAddress());
        System.out.println(new String(packet.getData(),0,packet.getData().length));

        socket.close();
    }
}
九、UDP聊天实现

发送方

package cn.bloghut.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(8080);
        while (true) {
            //准备数据
            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);
            if (data.equals("bye")) {
                break;
            }
        }

        socket.close();


    }
}

接收方

package cn.bloghut.chat;

import java.net.DatagramPacket;
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);//阻塞式接收包裹


            byte[] data = packet.getData();
            String receiveData = new String(data, 0, data.length);

            System.out.println(receiveData);

            //断开连接 bye
            if (receiveData.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1014147.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号