The service end is finished, now write a client, for the client, I consider using NIO or blocking sockets can.
Clients that use NIO:
1 /**2 * Initialize the network connection3 */4 Public voidrun () {5 6 //turn on the network connection7 Try {8Channel = Socketutils.connect ("127.0.0.1", 8080);9selector =Selector.open ();Ten Channel.register (selector, selectionkey.op_connect); One while(running) { A Selector.select (); -Iterator ite =Selector.selectedkeys (). iterator (); - while(Ite.hasnext ()) { theSelectionkey key =(Selectionkey) Ite.next (); - Ite.remove (); - ReadData (key); - } + } -}Catch(Throwable e) { +Logger.error ("Socket or other fail!", e); A}finally { at //Close Channel - if(Channel! =NULL) { - Try { - channel.close (); -}Catch(IOException e) { - e.printstacktrace (); in } - } to //Close Selector + if(Selector! =NULL) { - Try { the selector.close (); *}Catch(IOException e) { $ e.printstacktrace ();Panax Notoginseng } - } the } +}
Read the data in the same way as the server, do not write.
Here's how to block the socket:
1 Public voidrun () {2 byte[] buffer =New byte[512];3running =true;4 while(running) {5 Try {6Socket =NewSocket ("127.0.0.1", 8080);7InputStream InputStream =Socket.getinputstream ();8OutputStream OutputStream =Socket.getoutputstream ();9 Handleconnectlistener (ConnectListener.ConnectStatus.connected);Ten //reading Data One intBufferCount =-1; ABytebuffer Bytebuffer = bytebuffer.allocate (buffer.length*2); - messagehandler.initbytebuffersize (Bytebuffer.capacity ()); - while(BufferCount = inputstream.read (buffer)) >=0){ theBytebuffer.put (buffer,0, bufferCount); - //TODO parsing - } -}Catch(Exception e) { + e.printstacktrace (); - } + } A}
When the client is connected, it inherits the thread, and the call remembers start ().
Although the second instance does not use NIO, it is very useful to use Bytebuffer.
Introduction to Java NIO Network programming Services Chapter