Java NIO socket communication instance, niosocket

Source: Internet
Author: User

Java NIO socket communication instance, niosocket

Main differences between java Nio communication and Bio communication:

1. A single channel in Nio can support read operations or write operations, while the read operations in bio must use inputstream and the write operations must be outputstream.

2. nio uses byteBuffer as the memory cache and writes or degrees operations to the channel. bio basically uses byte []

3. nio uses the selector component to poll and read the ready channel


Server demo code:

package com.my.socket3;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.SelectionKey;import java.nio.channels.Selector;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.util.Iterator;import java.util.Set;import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;public class ServerTest {public static void main(String[] args) throws Exception {server();}public static void server(){ServerSocketChannel channel=null;try{Selector selector=Selector.open();channel=ServerSocketChannel.open();channel.configureBlocking(false);channel.socket().setReuseAddress(true); channel.bind(new InetSocketAddress(8020));channel.register(selector, SelectionKey.OP_ACCEPT,0);while(true){if(selector.select()>0){Set<SelectionKey> sets=selector.selectedKeys();Iterator<SelectionKey> keys=sets.iterator();while(keys.hasNext()){SelectionKey key=keys.next();keys.remove();if(key.isAcceptable()){SocketChannel schannel=((ServerSocketChannel) key.channel()).accept();schannel.configureBlocking(false);schannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);}if(key.isReadable()){SocketChannel schannel=(SocketChannel) key.channel();ByteBuffer buf=ByteBuffer.allocate(1024);ByteOutputStream output=new ByteOutputStream();int len=0;while((len=schannel.read(buf))!=0){buf.flip();byte by[]=new byte[buf.remaining()];buf.get(by);output.write(by);buf.clear();}System.out.println(new String(output.getBytes()));}if(key.isWritable()){SocketChannel schannel=(SocketChannel) key.channel();schannel.write(ByteBuffer.wrap((("server say:hi")).getBytes()));  }}}}}catch(Exception e){e.printStackTrace();}finally{if(channel!=null){try {channel.close();} catch (IOException e) {e.printStackTrace();}}}}}

Client demo code

package com.my.socket3;import java.io.ByteArrayOutputStream;import java.io.IOException;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 ClientTest {public static void main(String[] args) throws Exception {client();}public static void client() {SocketChannel channel=null;try {Selector selector=Selector.open();channel = SocketChannel.open();channel.configureBlocking(false);channel.connect(new InetSocketAddress(8020));channel.register(selector, SelectionKey.OP_CONNECT);while(true){if(selector.select()>0){Iterator<SelectionKey> set=selector.selectedKeys().iterator();while(set.hasNext()){SelectionKey key=set.next();set.remove();SocketChannel ch=(SocketChannel) key.channel();if(key.isConnectable()){ch.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);ch.finishConnect();}if(key.isReadable()){ByteArrayOutputStream output=new ByteArrayOutputStream();ByteBuffer buffer=ByteBuffer.allocate(1024);int len=0;while((len=ch.read(buffer))!=0){buffer.flip();byte by[]=new byte[buffer.remaining()];buffer.get(by);output.write(by);buffer.clear();}System.out.println(new String(output.toByteArray()));output.close();}if(key.isWritable()){ch.write(ByteBuffer.wrap((("client say:hi")).getBytes()));}}}}} catch (Exception e) {e.printStackTrace();}finally{try {channel.close();} catch (IOException e) {e.printStackTrace();}}}static class ClientRunnable implements Runnable{private SocketChannel ch;private ClientRunnable(SocketChannel ch){this.ch=ch;}@Overridepublic void run() {try {while(true){ch.write(ByteBuffer.wrap((("client say:hi")).getBytes()));Thread.sleep(5000);}} catch (Exception e) {e.printStackTrace();try {ch.close();} catch (IOException e1) {e1.printStackTrace();}}}}}

Problems encountered during demo running

1. The client needs to perform the ch. finishiCnonnect () operation, otherwise both sides will be blocked

2. When reading bytebuffer in the channel, while (len = ch. read (buffer ))! = 0) Judge not to write as while (len = ch. read (buffer ))! =-1)


How does java NIO implement communication between the client and the client? Does each connection have a specified ServerSocketChannel?

C/S is paired. If you want clients to communicate with each other, you can forward data through S. Another way is to tell each other where S is located and the ports are connected to each other through S.
Reference: zhidao.baidu.com/question/251295974

The java client uses Socket and the server uses SocketChannel. Can the two communication methods be implemented? I hope you can understand it.

Socket and ServerSocke are a pair of socket Communication classes under java.net.
SocketChannel and ServerSocketChannel are Communication classes under java. nio that support asynchronous communication.

The server must first establish a ServerSocket or ServerSocketChannel to wait for the Client Connection
The client must establish a Socket or SocketChannel to connect to the server.
The server receives the connection from the client and generates a Socket or SocketChannel to communicate with the client.

However, the Socket and SocketChannel can be converted to each other through the socket. channel () SocketChannel. socket () method.
Likewise, ServerSocket and ServerSocketChannel can be converted to each other.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.