In this article, the socket in Java can be divided into ordinary sockets and niosocket two kinds. How to use a common socket
The network communication in Java is realized through socket, socket is divided into serversocket and socket, ServerSocket is used for server, can listen to request through the Accept method, the receiver hears the request and returns the socket. The socket is used to complete the data transfer, and the client directly uses the socket to initiate the request and transfer data.
A simple interactive introduction to the use of ServerSocket and sockets: 1. Create a serversocket.
ServerSocket的构造方法一共有5个。最方便的是传入一个端口参数的方法。
2. Call the created ServerSocket's accept method to listen
accept方法是阻塞方法,也就是说调用accept方法后程序会停下来等待连接请求,在接收到请求之前程序将不会继续执行,当接收到请求之后,accept方法会返回一个Socket。
3. Use the socket returned by the Accept method to communicate with the client.
Examples of server-side code:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Date; Public class Server { Public Static voidMain (string[] args) {Try{//Create a Servesocket and set the port to 8080ServerSocket ServerSocket =NewServerSocket (8080);//Run socket listener, wait for request this method will block the thread and continue execution when requestedSocket socket = serversocket.accept ();//After receiving the request, use the socket to communicate, create BufferedReader to read the requested dataBufferedReaderinch=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); PrintWriter out =NewPrintWriter (Socket.getoutputstream ()); String line =inch. ReadLine (); System.out.println (line);//Create printlnwriter for sending dataOut.println ("The data has been accepted."); Out.flush (); System.out.println ("Server Shutdown"+NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss.sss"). Format (NewDate ()));//Close ResourcesOut.close ();inch. Close (); Socket.close (); Serversocket.close (); }Catch(IOException e) {E.printstacktrace (); }finally{ } }}
Sample client code:
ImportJava.io.BufferedReader;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.Socket;ImportJava.text.SimpleDateFormat;ImportJava.util.Date;/** * Client * @author Sanchan * * Public class Client { Public Static void Main(string[] args) {//need to start the server first otherwise error java.net.ConnectException:Connection refused Try{String msg="Hello, serversocket!.";//Create a socket to connect to the native 8080 portSocket socket=NewSocket ("127.0.0.1",8080);//Using sockets to create PrintWriter and BufferedReader for data reading and writingPrintWriter out=NewPrintWriter (Socket.getoutputstream ()); OUT.PRINTLN (msg); Out.flush (); BufferedReader in=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); String Line=in.readline (); System.out.println (line);//Close ResourcesIn.close (); Out.close (); Socket.close (); System.out.println ("Client Off"+NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss.sss"). Format (NewDate ())); }Catch(Exception e) {E.printstacktrace (); }finally{ } }}
Use of Niosocket
NIO (new IO) is the newly added IO mode of JDK1.4, and NIO uses new processing methods to greatly improve the efficiency of Java IO. Sockets are also part of the IO, and NIO provides the corresponding classes: Serversocketchannel and Socketchannel, respectively, corresponding to the original serversocket and sockets.
Understanding the three Fundamentals of NiO: 1. Buffer2. Channel3. There is great wisdom in the selector little story:
Imagine if the e-commerce is as long as there is an order to send someone to take the goods directly to the delivery "this model is equivalent to the previous socket way", rather than the current mode of delivery: the goods are unified to the transfer station, the sorter according to the distribution range distribution courier, and then courier unified Delivery " This mode is equivalent to Niosocket mode ". So how long do you have to receive your courier/(ㄒoㄒ)/~~
Buffer is the cargo, the channel is The Courier, selector is the station's sorter.
Niosocket Use steps: 1. Create Serversocketchannel and set corresponding parameters
SerSocketChannel可以使用自身的静态工厂方法open创建。每个ServerSocketChannel对应一个ServerSocket,可以调用其socket方法来获取【不过如果使用该ServerSocket监听请求就又回到原来的 普通Socket 模式了,一般只用于使用bind方法绑定端口】。ServerSocketChannel可以通过`SelectableChannel configureBlocking(boolean block)` 方法来设置是否采用阻塞模式。设置非阻塞模式之后可以调用register方法注册Selector【阻塞模式不可以使用Selector】
2. Create selector and register selector to Serversocketchannel
Selector可以使用自身的静态工厂方法open创建。创建后通过上面所说的Channel的register方法注册到ServerSocketChannel或者SocketChannel上。
3. Call Selector's Select method to wait for the request
通过select方法等待请求,select方法可传入代表最长等待时间的long型参数。在设定时间内接收到相应操作的请求则返回可以处理请求的数量,否则在超时后返回0,程序继续执行。如果传入0或者使用无参的重载方法,则会采用阻塞模式直到有相应操作的请求出现。
4. Use selector to receive requests and process
接收到请求后Selector调用selectedKeys返回SelectionKey的Set集合。
5. Use Selectionkey to obtain channel, selector, and operation types and perform specific operations.
SelectionKey保存了处理当前请求的Channel和Selector,并提供了不同的操作类型。前面提到的Channel注册Selector的register方法参数中第二个参数就是SelectionKey定义的。共有四种:
SelectionKey.OP_ACCEPT //请求操作SelectionKey.OP_CONNECT //链接操作SelectionKey.OP_READ //读操作SelectionKey.OP_WRITE //写操作
only the corresponding operation selector registered in the Register method will be concerned with the request of the corresponding type operation.
Selector and channel are many-to-many relationships.
Selector is sorted according to different operation types, the sorting results are stored in Selectionkey, and the channel and selector can be obtained by Selectionkey Channel and selector method respectively. You can use Selectionkey's isacceptable, isconnectable, IsReadable, and iswritable methods to determine what type of operation is.
Buffer is dedicated to storing data and has four extremely important properties:
- Capacity: capacity.
Buffer can hold up to the number of elements, set when created, and cannot be modified during use.
- Limit: The maximum amount that can be used.
The limit equals capacity when the buffer was first created. If the limit is set to "cannot exceed capacity", the limit becomes the maximum accessible value.
For example, a buffer of capacity is 100, which means that you can save up to 100 data, write only 20 and then read, and limit will be set to 20 when reading.
- Position: The index position at which the currently manipulated element is located.
Position starts with 0 and is automatically updated with the get and put methods.
- Mark: The value used to temporarily save the position.
After the position is saved to mark, it can be modified and related, and the Reset method restores Mark's value to position after the operation is completed.
The mark default value is-1, and its value must be less than the value of position.
For example, a total of 20 data is saved in buffer, position is 10, and now you want to read data between 15 and 20, you can call buffer's Mark method to save the current position to mark, and then call the position in buffer ( 15) Point the position to the 15th element and you can read it. After reading is complete, the position can be restored to 10 using the buffer reset.
If the value passed in when calling the position method of buffer is less than the current value of Mark, Mark will be set to-1.
These four attribute size relationships: mark<=position<=limit<=capacity
Let's rewrite the service side of the previous common socket example:
ImportJava.io.IOException;Importjava.net.InetSocketAddress;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.SelectionKey;ImportJava.nio.channels.Selector;ImportJava.nio.channels.ServerSocketChannel;ImportJava.nio.channels.SocketChannel;ImportJava.nio.charset.Charset;ImportJava.util.Iterator;/** * @author Sanchan * @since 1.0 * * Public class nioserver { Public Static void Main(string[] args) {/** * Start monitoring * When the listener hears the request according to the Selectionkey operation type to the internal class handler for processing * * Try{//Create ServersocketchannelServersocketchannel SSC = Serversocketchannel.open ();//Set listening 8080 portSsc.socket (). Bind (NewInetsocketaddress (8080));//Set to non-blocking modeSsc.configureblocking (false);//For Serversocketchannel registration selectorSelector Selector = Selector.open (); Ssc.register (selector, selectionkey.op_accept);//Create HandlerHandler Handler =NewHandler (1024x768); while(true) {//wait for a request, each time it waits for 3s, the thread continues to run after more than 3 seconds, and will block if passed in 0 or using the no-parameter overloaded method if(Selector.select ( the) ==0) {System.out.println ("Waiting for Request timeout ~~~~~");Continue; } System.out.println ("Processing request ~~~~~");//Get Selectionkey waiting to be processediterator<selectionkey> keyiterator = Selector.selectedkeys (). Iterator (); while(Keyiterator.hasnext ()) {Selectionkey key = Keyiterator.next ();Try{//Select the corresponding processing method according to different request operation if(Key.isacceptable ()) {handler.handleaccept (key); }if(Key.isreadable ()) {Handler.handleread (key); } }Catch(IOException e) {E.printstacktrace ();//If the exception indicates the end of the connection, removeKeyiterator.remove ();Continue; } } } }Catch(IOException e) {E.printstacktrace (); }finally{ } }/** * Request Processing class * / Private Static class Handler { Private intBufferSize =1024x768;PrivateString Localcharset ="UTF-8"; Public Handler() { } Public Handler(intbuffersize) { This(BufferSize,NULL); } Public Handler(String Localcharset) { This(-1, Localcharset); } Public Handler(intBufferSize, String localcharset) {if(BufferSize >0) This. buffersize = buffersize;if(Localcharset! =NULL) This. Localcharset = Localcharset; }/** * Processing Request operation * * @param key * @throws ioexception */ Public void handleaccept(Selectionkey key)throwsIOException {//Access channelSocketchannel sc = ((serversocketchannel) Key.channel ()). Accept ();//Set non-blockingSc.configureblocking (false);//Selector of registered read operationsSc.register (Key.selector (), Selectionkey.op_read, Bytebuffer.allocate (buffersize)); }/** * Processing Read operation * * @param key * @throws ioexception */ Public void Handleread(Selectionkey key)throwsIOException {//Access channelSocketchannel sc = ((socketchannel) Key.channel ());//Get Bytebuffer /** * Buffer is dedicated to storing data and has four extremely important properties: * 1. Capacity: capacity. * Buffer can hold up to the number of elements, set when created, and cannot be modified during use. * 2. Limit: The maximum amount that can be used. * Limit equals capacity when buffer is created. If the limit is set to "cannot exceed capacity", the limit becomes the maximum accessible value. * For example, a buffer of capacity is 100, which means that you can save up to 100 data, write only 20 and then read, and limit will be set to 20 when reading. * 3. Position: The index position at which the currently manipulated element is located. * Position starting from 0, with the get and put methods automatically updated. * 4. Mark: The value used to temporarily save the position. * position is saved to mark and can be modified and related, and the Reset method will restore Mark's value to position after the operation is completed. * Mark Default value is-1, and its value must be less than the value of position. * For example, a total of 20 data is saved in buffer, position is 10, and now you want to read data between 15 and 20, you can call buffer's Mark method to save the current position to mark, and then call buffer position (15) The position is pointed to the 15th element, then it can be read. After reading is complete, the position can be restored to 10 using the buffer reset. * If the value passed in when calling buffer's position method is less than the current value of Mark, Mark will be set to-1. */Bytebuffer buffer = (bytebuffer) key.attachment ();//Reset Bytebuffer. Set limit=capacity, position=0, Mark=-1Buffer.clear ();//Do not get content to close if(sc.read (buffer) = =-1) {sc.close (); }Else{/** * Flip () Effect: * Save data with a data position plus 1, after saving to read the data * you have to set the Limit=positi On,position=0 **/Buffer.flip ();//Return data to clientString receivedstring = Charset.forname (localcharset). Newdecoder (). Decode (buffer). toString (); System.out.println ("Data was obtained from the client:"+ receivedstring); String sendstring ="The server has acquired the data:"+ receivedstring; Buffer = Bytebuffer.wrap (Sendstring.getbytes (Localcharset)); Sc.write (buffer);//Close SocketchannelSc.close (); } } }}
Java Socket Exploration