search
Home类库下载java类库java NIO socket programming
java NIO socket programmingOct 13, 2016 pm 03:27 PM

In java socket programming, most generally use blocking IO socket programming. Socket reading and writing will block (that is, calling the read and write methods will block regardless of whether there is currently written/read data). NIO registers I/O events and notifies you when a specific registered I/O event arrives. There is no need to poll or create a large number of threads. Here is an example: Download the

Server code

package simple.socket;  
  
import java.io.IOException;  
import java.net.InetSocketAddress;  
import java.net.ServerSocket;  
import java.nio.ByteBuffer;  
import java.nio.channels.*;  
import java.util.Iterator;  
import java.util.Set;  
  
/**  
 * Created by banxia on 16/10/12.  
 */  
public class UseNioSocket {  
  
  
    public static void main(String[] args) throws IOException {  
  
        // 创建一个selector 对象  
        Selector selector = Selector.open();  
  
        ServerSocketChannel ssc = ServerSocketChannel.open();  
        ssc.configureBlocking(false);  
        ssc.socket().bind(new InetSocketAddress(8888));  
        ssc.register(selector, SelectionKey.OP_ACCEPT);  
        ByteBuffer buffer = ByteBuffer.allocate(1024);  
  
        System.out.println("服务已经启动端口:" + 8888);  
  
        while (true) {  
  
            int selectNum = selector.select();  
            System.out.println("selectNum=" + selectNum);  
  
            if (selectNum <= 0) {  
                continue;  
            }  
            // 获取  
  
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();  
  
            while (it.hasNext()) {  
  
                SelectionKey key = it.next();  
  
                if (key.readyOps() == SelectionKey.OP_ACCEPT) {  
                    // 接收 accept  
  
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();  
                    SocketChannel accept = channel.accept();  
                    accept.configureBlocking(false);  
                    System.out.println("接收客户端:" + accept.socket().getInetAddress().getHostAddress() + ":" +  accept.socket().getPort());  
                    accept.register(selector, SelectionKey.OP_READ);  
                    it.remove();  
  
  
                } else {  
  
                    SocketChannel sc = (SocketChannel) key.channel();  
                    System.out.println("接收客户端:" + sc.socket().getInetAddress().getHostAddress() + ":" + sc.socket().getPort() +"开始处理...");  
                    while (true) {  
                        buffer.clear();  
                        long l = sc.read(buffer);  
                        if (l <= 0) {  
                            break;  
                        }  
                        System.out.print(".");  
                        buffer.flip();  
                        sc.write(buffer);  
  
  
                    }  
                    System.out.print("\n");  
                    it.remove();  
                    System.out.println("接收客户端:" + sc.socket().getInetAddress().getHostAddress() + ":" + sc.socket().getPort() +"处理完成处理...");  
  
                }  
  
            }  
  
  
        }  
  
  
    }  
}


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)