2016年10月18日 星期二

Java Networking and Java NIO Tutorial and Notes

Java Networking
http://tutorials.jenkov.com/java-networking/index.html

Java standard IO works with byte streams and character streams, blocking.

How to create a TCP socket to connect to a server?
Use Socket, getOutputStream, write, flush then close.
Use Socket, getInputStream, read, in.close, socket.close.

How to create a server that listens to incoming TCP connections?
Use ServerSocket, accept, socket.close, serverSocket.close.

How to send data using UDP socket?
Prepare new byte[65508], InetAddress.getByName and DatagramPacket
Use DatagramSocket().send(DatagramPacket)

How to receive data using UDP socket?
Use DatagramSocket to specify the UDP port, byte[], DatagramPacket.receive which is a blocking method.

How to read the HTTP web content?
Use URL and URLConnection.getInputStream

How to create an IP address?
Use InetAddress.getByName("google.com"), getByName("1.2.3.4") or getLocalHost()

Java NIO
http://tutorials.jenkov.com/java-nio/index.html

Java NIO works with channels and buffers, non-blocking, selectors.
A single thread uses a single selector that monitors multiple channels for events like connection opened or data arrived.

Java NIO core classes: Channel, Buffer, Selector

For Channel, the implementations are FileChannel, DatagramChannel, SocketChannel, ServerSocketChannel

For Buffer, the implementations are ByteBuffer, CharBuffer, DoubleBuffer, FloatBuffer, IntBuffer, LongBuffer, ShortBuffer. They are essentially the 8 Java primitives except Boolean.


沒有留言:

張貼留言