JAVA系列教程:网络编程

基本概念

在开始讲解java中如何实现网络编程之前,我们先了解一下几个基本概念

  1. IO–主要是指对文件,网络socket以及外设的操作,这里会涉及到linux的用户态和内核态(所有对磁盘文件,网络socket以及外设的操作都需要通过内核态进行访问),具体如下:

A.用户通过系统调用向内核态发送访问磁盘文件,网络socket以及外设操作请求
B.内核态检查数据是否已经就绪,如果准备就绪则将数据从磁盘文件,网络socket或外设拷贝到系统态的内存中
C.将内核态的数据拷贝到用户空间(如图中就拷贝到JVM堆中),供应用程序使用。
在这里插入图片描述

  1. 同步与异步

同步:即发出一个调用请求之后,将一直等待该请求处理完成才进行返回

异步:即发出一个调用请求之后立即返回,没有实时返回结果,在请求处理完成之后,被调用者通过状态,通知来回调告诉被调用者处理结果.

  1. 阻塞IO与非阻塞IO

阻塞IO:即发送IO请求之后,将一直到数据就绪并完成拷贝之后才会返回

非阻塞IO:即发送IO请求之后,如果数据还没就绪,则返回一个标记来告知用户线程用户数据仍然还没准备就绪

  1. BIO与NIO

BIO: Blocking IO,即同步阻塞IO,即当请求发送之后,一直要等网络数据就绪之后才会返回

NIO: Non-Blocking IO,即同步非阻塞IO,即请求发送之后,如果网络数据还没就绪,则通过一个标记来告知用户线程数据仍然还未就绪。

Java BIO 与NIO具体实现图解

在这里插入图片描述

在这里插入图片描述

BIO代码实现

Code for Server

package com.mary.demo;

import com.sun.javafx.scene.traversal.SubSceneTraversalEngine;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSocketDemo {
    public static void main(String[] args) throws Exception{
        ServerSocketDemo demo = new ServerSocketDemo();
        demo.createSocketAndBind();
    }

    private void createSocketAndBind() throws Exception{
        ServerSocket serverSocket = new ServerSocket(8888);
        while(true){
            Socket socket = serverSocket.accept();
            Thread thread = new Thread(new SocketHandlerTask(socket));
            thread.run();
        }
    }

    public static class SocketHandlerTask implements Runnable{
        private Socket socket;
        private InputStream inputStream;
        private OutputStream outputStream;

        public SocketHandlerTask(Socket socket){
            this.socket = socket;
            try{
                this.inputStream = socket.getInputStream();
                this.outputStream = socket.getOutputStream();
            }catch (Exception ex){
                System.err.println("init stream error" + ex);
            }
        }

        @Override
        public void run() {
            try{
                System.out.println("Begin Handler the socket");
                BufferedReader br = new BufferedReader(new InputStreamReader(this.inputStream));
                PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(this.outputStream), true);
                while(true){
                    String msgData = br.readLine();
                    System.out.println(new String("receive from client: " +  msgData));

                    if("exit".equals(msgData)){
                        break;
                    }

                    //send the msg to the client
                    String msg = "Hello, client, I am server";
                    printWriter.println(msg);
                    outputStream.flush();
                }
                this.outputStream.close();
                this.inputStream.close();
                this.socket.close();

            }catch (Exception ex){
                System.err.println("run error" + ex);
            }

        }
    }
}

Code for Client

package com.mary.demo;

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

public class ClientSocketDemo {
    public static void main(String[] args) throws Exception{
        Socket socket = new Socket("192.168.0.13", 8888);
        //get the inputstream and outputstream to read and write data
        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        while(true){
            String msg = "hello, I am client";
            //write the length
            PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream), true);
            printWriter.println(msg);
            outputStream.flush();

            //read message from the server
            String msgFromServer = br.readLine();
            System.out.println("Read from Server: " + msgFromServer);
            if("exit".equals(msgFromServer)){
                break;
            }

        }
    }
}

NIO代码实现

NIO Server

package com.mary.demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NIOServerSocketDemo {
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;

    public static void main(String[] args){
        int port = 8888;
        NIOServerSocketDemo demo = new NIOServerSocketDemo();
        demo.init(port);
        demo.start();
    }

    public void init(int port){
        try{
            this.serverSocketChannel = ServerSocketChannel.open();
            this.serverSocketChannel.socket().bind(new InetSocketAddress(port));
            this.serverSocketChannel.configureBlocking(false);

            this.selector = Selector.open();
            this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT);
        }catch (Exception ex){
            System.err.println("Init error"+  ex);
        }
    }

    public void start(){
        while(true){
            try{
                this.selector.select();
                Set<SelectionKey> selectionKeySet = this.selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeySet.iterator();
                while(iterator.hasNext()){
                    SelectionKey sk = iterator.next();
                    if(sk.isAcceptable()){
                        ServerSocketChannel serverSocketChannel = (ServerSocketChannel)sk.channel();
                        handleAcceptor(serverSocketChannel);
                    }
                    if(sk.isReadable()){
                        //read data from the socket
                        SocketChannel socketChannel = (SocketChannel)sk.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        socketChannel.read(byteBuffer);
                        //print the message
                        byte[] array = byteBuffer.array();
                        String msgFromClient = new String(array, "utf-8");
                        System.out.println("Receive data from the client: " + msgFromClient);

                        if ("exit".equalsIgnoreCase(msgFromClient)) {
                            socketChannel.close();
                        }
                        String msg = "Hi I am server";
                        //获取发送消息用的buffer,wrap方法
                        ByteBuffer out = ByteBuffer.wrap(msg.getBytes());
                        //写入channel
                        socketChannel.write(out);
                    }
                    iterator.remove();
                }
            }catch (Exception ex) {
                System.err.println("start execute error" + ex.getMessage());
            }
        }
    }

    private void handleAcceptor(ServerSocketChannel serverSocketChannel) throws IOException {
        SocketChannel socketChannel = serverSocketChannel.accept();
        if(socketChannel == null){
            return;
        }
        socketChannel.configureBlocking(false);
        socketChannel.register(this.selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
    }
}

NIO Client

package com.mary.demo;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOClientSocketDemo {
    private SocketChannel socketChannel;
    private Selector selector;
    private volatile boolean hasSendMessage = false;

    public static void main(String[] args){
        NIOClientSocketDemo socketDemo = new NIOClientSocketDemo();
        socketDemo.init();
        socketDemo.start();
    }

    public void init(){
        try{
            this.socketChannel = SocketChannel.open();

            this.selector = Selector.open();

            this.socketChannel.socket().connect(new InetSocketAddress(8888));
            this.socketChannel.configureBlocking(false);
            this.socketChannel.register(this.selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

        }catch (Exception ex){
           System.err.println("init error" + ex);
        }
    }

    public void start(){
        while(true){
            try{
                this.selector.select();
                Set<SelectionKey> selectionKeySet = this.selector.selectedKeys();
                Iterator<SelectionKey> selectionKeyIterator = selectionKeySet.iterator();
                while(selectionKeyIterator.hasNext()){
                    SelectionKey selectionKey = selectionKeyIterator.next();
                    if(selectionKey.isReadable()) {
                        //read message from the server
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        socketChannel.read(byteBuffer);
                        byte[] array = byteBuffer.array();
                        System.out.println("receive from server: " + new String(array, "utf-8"));
                    }
                    if(selectionKey.isWritable() && !hasSendMessage){
                        //write some message to the client
                        SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
                        String msg = "hi, I am client";
                        ByteBuffer sendMsgBuffer = ByteBuffer.wrap(msg.getBytes("utf-8"));
                        socketChannel.write(sendMsgBuffer);
                        this.hasSendMessage = true;
                    }
                    selectionKeyIterator.remove();
                }
            }catch (Exception ex){
                System.err.println("start error" + ex);
            }

        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值