java网络编程

来源:互联网 发布:java图形接口 编辑:程序博客网 时间:2024/06/16 22:11

主要内容:

网络编程概述
通讯要素
IP和端口号
网络通信协议
InetAddress
TCP网络通信
UDP网络通信
URL编程

计算机网络:

     把分布在不同地理区域的计算机与专门的外部设备用通信线路互连成一个规模大、功能强的网络系统,从而使众多的计算机可以方便地互相传递信息、共享硬件、软件、数据信息等资源。

网络编程的目的:

     直接或间接地通过网络协议与其它计算机进行通讯

网络编程中有两个主要的问题:
如何准确地定位网络上一台或多台主机
找到主机后如何可靠高效地进行数据传输

IP 地址:InetAddress
唯一的标识 Internet 计算机

端口标识正在计算机上运行的进程(程序
不同的进程有不同的端口号
IP地址端口共同组成网络套接字
InetAddress:
  
      InetAddress address=InetAddress.getByName("www.atguigu.com");//通过域名获取一个InetAddress对象
        InetAddress local=InetAddress.getLocalHost();//获取本地的主机
        System.out.println(address);//www.atguigu.com/42.121.6.2
        System.out.println(address.getHostName());//www.atguigu.com hostName 域名
        System.out.println(address.getHostAddress());//42.121.6.2 hostAddress ip地址

在浏览器的地址栏输入网络链接之后的访问过程:
http://www.atguigu.com----->先找本机hosts,是否有输入的域名地址-------->本地没有,DNS(域名解析器)
示意图:


传输层协议中有两个非常重要的协议:
传输控制协议TCP(Transmission Control Protocol)
用户数据报协议UDP(User Datagram Protocol)
TCP/IP 其两个主要协议:传输控制协议(TCP)和网络互联协议(IP)而得名,实际上是一组协议,包括多个具有不同功能且互为关联的协议

TCP协议(类似打电话):
使用TCP协议前,须先建立TCP连接,形成传输数据通道
传输前,采用“三次握手”方式,是可靠的
TCP协议进行通信的两个应用进程:客户端、服务端
在连接中可进行大数据量的传输
传输完毕,需释放已建立连接,效率低
UDP协议(类似邮寄东西):
将数据、源、目的封装成数据包,不需要建立连接
每个数据报的大小限制在64K
因无需连接,故是不可靠的
发送数据结束时无需释放资源,速度快

Socket:

利用套接字(Socket)开发网络应用程序早已被广泛的采用,以至于成为事实上的标准
通信的两端都要有Socket,是两台机器间通信的端点
网络通信其实就是Socket间的通信。
Socket允许程序把网络连接当成一个流,数据在两个Socket间通过IO传输
一般主动发起通信的应用程序属客户端,等待通信请求的        

  服务


代码示例一:客户端给服务端发送信息。服务端输出此信息到控制台上

    // 客户端
    @Test
    public void client() {
        Socket socket = null;
        OutputStream os = null;
        try {
            // 1.创建一个Socket的对象,通过构造器指明服务端的IP地址,以及其接收程序的端口号
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
            // 2.getOutputStream():发送数据,方法返回OutputStream的对象
            os = socket.getOutputStream();
            // 3.具体的输出过程
            os.write("我是客户端,请多关照".getBytes());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // 4.关闭相应的流和Socket对象
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }

    }

    // 服务端
    @Test
    public void server() {
        ServerSocket ss = null;
        Socket s = null;
        InputStream is = null;
        try {
            // 1.创建一个ServerSocket的对象,通过构造器指明自身的端口号
            ss = new ServerSocket(9090);
            // 2.调用其accept()方法,返回一个Socket的对象
            s = ss.accept();
            // 3.调用Socket对象的getInputStream()获取一个从客户端发送过来的输入流
            is = s.getInputStream();
            // 4.对获取的输入流进行的操作
            byte[] b = new byte[20];
            int len;
            while ((len = is.read(b)) != -1) {
                String str = new String(b, 0, len);
                System.out.print(str);
            }
            System.out.println("收到来自于" + s.getInetAddress().getHostAddress()
                    + "的连接");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // 5.关闭相应的流以及Socket、ServerSocket的对象
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
    }
}

代码示例二:客户端给服务端发送信息,服务端将信息打印到控制台上,同时发送“已收到信息”给客户端

//客户端
    @Test
    public void client(){
        Socket socket = null;
        OutputStream os = null;
        InputStream is = null;
        try {
            socket = new Socket(InetAddress.getByName("127.0.0.1"),8989);
            os = socket.getOutputStream();
            os.write("我是客户端".getBytes());
            //shutdownOutput():执行此方法,显式的告诉服务端发送完毕!
            socket.shutdownOutput();
            is = socket.getInputStream();
            byte[] b = new byte[20];
            int len;
            while((len = is.read(b)) != -1){
                String str = new String(b,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
        }
        
        
    }
    //服务端
    @Test
    public void server(){
        ServerSocket ss = null;
        Socket s = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            ss = new ServerSocket(8989);
            s = ss.accept();
            is = s.getInputStream();
            byte[] b = new byte[20];
            int len;
            while((len = is.read(b)) != -1){
                String str = new String(b,0,len);
                System.out.print(str);
            }
            os = s.getOutputStream();
            os.write("我已收到你的情意".getBytes());
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
            if(s != null){
                try {
                    s.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
            if(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
        }
        
    }
}

UDP网络通信:

DatagramSocketDatagramPacket实现基于UDP 协议网络程序
UDP数据报通过数据报套接字 DatagramSocket发送和接收,系统不保证UDP数据报一定能够安全送到目的地,也不能确定什么时候可以抵达
DatagramPacket对象封装了UDP数据报,在数据报中包含了发送端的IP地址和端口号以及接收端的IP地址和端口号
UDP协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和接收方的连接

示例代码:
@Test
    public void send() {
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket();
            byte[] b = "你好,我是要发送的数据".getBytes();
            //创建一个数据报:每一个数据报不能大于64k,都记录着数据信息,发送端的IP、端口号,以及要发送到
            //的接收端的IP、端口号。
            DatagramPacket pack = new DatagramPacket(b, 0, b.length,
                    InetAddress.getByName("127.0.0.1"), 9090);
            
            ds.send(pack);
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(ds != null){
                ds.close();
                
            }
        }
        
    }

    // 接收端
    @Test
    public void rceive() {
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket(9090);
            byte[] b = new byte[1024];
            DatagramPacket pack = new DatagramPacket(b, 0, b.length);
            ds.receive(pack);
            
            String str = new String(pack.getData(), 0, pack.getLength());
            System.out.println(str);
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(ds != null){
                ds.close();
                
            }
        }    
    }

URL编程:
URL(Uniform Resource Locator):统一资源定位符,表示Internet 某一资源的地址。通过URL 我们可以访问Internet 的各种网络资源,比如最常见wwwftp站点。浏览器通过解析给定URL 可以在网络上查找相应的文件或其他资源。
URL的基本结构由5部分组成
<传输协议>://<主机名>:<端口号>/<文件名>
例如: http://192.168.1.100:8080/helloworld/index.jsp

示例代码:
//1.创建一个URL的对象
        URL url = new URL("http://127.0.0.1:8080/examples/HelloWorld.txt?a=b");//File file = new File("文件的路径");
        //如何将服务端的资源读取进来:openStream()
        InputStream is = url.openStream();
        byte[] b = new byte[20];
        int len;
        while((len = is.read(b)) != -1){
            String str = new String(b,0,len);
            System.out.print(str);
        }
        is.close();
//如果既有数据的输入,又有数据的输出,则考虑使用URLConnection
       URLConnection connection = url.openConnection();
        OutputStream os = connection.getOutputStream();




0 0
原创粉丝点击