{"id":28916,"date":"2015-11-27T21:00:59","date_gmt":"2015-11-27T19:00:59","guid":{"rendered":"http:\/\/examples.javacodegeeks.com\/?p=28916"},"modified":"2019-03-19T13:19:02","modified_gmt":"2019-03-19T11:19:02","slug":"java-nio-socket-example","status":"publish","type":"post","link":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/","title":{"rendered":"Java Nio Socket Example"},"content":{"rendered":"<p>This article introduces the <code>SocketChannel<\/code> class and its basic usage. This class is defined in the java.nio package.<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;\n<\/p>\n<h2>1. Standard Java sockets<\/h2>\n<p>Socket programming involves two systems communicating with one another. In implementations prior to NIO, Java TCP client socket code is handled by the java.net.Socket class. A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes, <code>Socket<\/code> and <code>ServerSocket<\/code>, that implement the client side of the connection and the server side of the connection, respectively. The below image illustrates the nature of this communication:<\/p>\n<p><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/11\/socket.jpg\"><img decoding=\"async\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/11\/socket.jpg\" alt=\"socketExample\" width=\"860\" height=\"364\" class=\"alignnone size-full wp-image-29387\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/11\/socket.jpg 860w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/11\/socket-300x127.jpg 300w\" sizes=\"(max-width: 860px) 100vw, 860px\" \/><\/a><\/p>\n<p>A socket is basically a blocking input\/output device. It makes the thread that is using it to block on reads and potentially also block on writes if the underlying buffer is full. Therefore, different threads are required if the server has many open sockets. From a simplistic perspective, the process of a blocking socket communication is as follows:<\/p>\n<ul>\n<li>Create a <code>ServerSocket<\/code>, specifying a port to listen on.<\/li>\n<li>Invoke the ServerSocket&#8217;s <code>accept()<\/code> method to listen on the configured port for a client connection.<\/li>\n<li>When a client connects to the server, the <code>accept()<\/code> method returns a <code>Socket<\/code> through which the server can communicate with the client:&nbsp;an <code>InputStream<\/code> is obtained to read from the client and an <code>OutputStream<\/code> to write to the client.<\/li>\n<\/ul>\n<h2>2. Nonblocking SocketChannel with java.nio<\/h2>\n<p>With the standard java sockets, if the server needed to be scalable, the socket had to be passed to another thread for processing&nbsp;so that the server could continue listening for additional connections, meaning call the ServerSocket&#8217;s <code>accept()<\/code> method again to listen for another connection.<\/p>\n<p>A <code>SocketChannel<\/code> on the other hand is a non-blocking way to read from sockets,&nbsp;so that you can have one thread communicate with multiple open connections at once. With socket channel we describe the communication channel between client and server.&nbsp;It is identified by the server IP address and the port number. Data passes through the socket channel by buffer items. A selector monitors the recorded socket channels and serializes the requests, which the server has to satisfy.&nbsp;The Keys describe the objects used by the selector to sort the requests.&nbsp;Each key represents a single client sub-request and contains information to identify the client and the type of the request. With non-blocking I\/O, someone can program networked applications to handle multiple simultaneous connections without having to manage multiple thread collection, while also taking advantage of the new server scalability that is built in to java.nio. The below image illustrates this procedure:<br \/>\n<a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/11\/socketchannel.jpg\"><img decoding=\"async\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/11\/socketchannel.jpg\" alt=\"socketchannel\" width=\"860\" height=\"344\" class=\"alignnone size-full wp-image-29388\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/11\/socketchannel.jpg 860w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/11\/socketchannel-300x120.jpg 300w\" sizes=\"(max-width: 860px) 100vw, 860px\" \/><\/a><\/p>\n<h2>3. Example<\/h2>\n<p>The following example shows the use of <code>SocketChannel<\/code> for creating a simple echo server, meaning it echoes back any message it receives.<\/p>\n<h3>3.1. The Server code<\/h3>\n<pre class=\"brush:java\">import java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.SelectionKey;\nimport java.nio.channels.Selector;\nimport java.nio.channels.ServerSocketChannel;\nimport java.nio.channels.SocketChannel;\nimport java.util.*;\n\npublic class SocketServerExample {\n\tprivate Selector selector;\n    private Map&lt;SocketChannel,List&gt; dataMapper;\n    private InetSocketAddress listenAddress;\n    \n    public static void main(String[] args) throws Exception {\n    \tRunnable server = new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\t try {\n\t\t\t\t\tnew SocketServerExample(\"localhost\", 8090).startServer();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t};\n\t\t\n\t\tRunnable client = new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\t try {\n\t\t\t\t\t new SocketClientExample().startClient();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t};\n       new Thread(server).start();\n       new Thread(client, \"client-A\").start();\n       new Thread(client, \"client-B\").start();\n    }\n\n    public SocketServerExample(String address, int port) throws IOException {\n    \tlistenAddress = new InetSocketAddress(address, port);\n        dataMapper = new HashMap&lt;SocketChannel,List&gt;();\n    }\n\n    \/\/ create server channel\t\n    private void startServer() throws IOException {\n        this.selector = Selector.open();\n        ServerSocketChannel serverChannel = ServerSocketChannel.open();\n        serverChannel.configureBlocking(false);\n\n        \/\/ retrieve server socket and bind to port\n        serverChannel.socket().bind(listenAddress);\n        serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);\n\n        System.out.println(\"Server started...\");\n\n        while (true) {\n            \/\/ wait for events\n            this.selector.select();\n\n            \/\/work on selected keys\n            Iterator keys = this.selector.selectedKeys().iterator();\n            while (keys.hasNext()) {\n                SelectionKey key = (SelectionKey) keys.next();\n\n                \/\/ this is necessary to prevent the same key from coming up \n                \/\/ again the next time around.\n                keys.remove();\n\n                if (!key.isValid()) {\n                    continue;\n                }\n\n                if (key.isAcceptable()) {\n                    this.accept(key);\n                }\n                else if (key.isReadable()) {\n                    this.read(key);\n                }\n            }\n        }\n    }\n\n    \/\/accept a connection made to this channel's socket\n    private void accept(SelectionKey key) throws IOException {\n        ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();\n        SocketChannel channel = serverChannel.accept();\n        channel.configureBlocking(false);\n        Socket socket = channel.socket();\n        SocketAddress remoteAddr = socket.getRemoteSocketAddress();\n        System.out.println(\"Connected to: \" + remoteAddr);\n\n        \/\/ register channel with selector for further IO\n        dataMapper.put(channel, new ArrayList());\n        channel.register(this.selector, SelectionKey.OP_READ);\n    }\n    \n    \/\/read from the socket channel\n    private void read(SelectionKey key) throws IOException {\n        SocketChannel channel = (SocketChannel) key.channel();\n        ByteBuffer buffer = ByteBuffer.allocate(1024);\n        int numRead = -1;\n        numRead = channel.read(buffer);\n\n        if (numRead == -1) {\n            this.dataMapper.remove(channel);\n            Socket socket = channel.socket();\n            SocketAddress remoteAddr = socket.getRemoteSocketAddress();\n            System.out.println(\"Connection closed by client: \" + remoteAddr);\n            channel.close();\n            key.cancel();\n            return;\n        }\n\n        byte[] data = new byte[numRead];\n        System.arraycopy(buffer.array(), 0, data, 0, numRead);\n        System.out.println(\"Got: \" + new String(data));\n    }\n}<\/pre>\n<p>From the above code:<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<ul>\n<li>In the <code>main()<\/code> method on lines 43-45, one thread for creating the <code>ServerSocketChannel<\/code> is started and two client threads responsible for starting the clients which will create a <code>SocketChannel<\/code> for sending messsages to the server.\n<pre class=\"brush:java\">new Thread(server).start();\nnew Thread(client, \"client-A\").start();\nnew Thread(client, \"client-B\").start();<\/pre>\n<\/li>\n<li>In the <code>startServer()<\/code> method on line 54, &nbsp;the server <code>SocketChannel<\/code> is created as nonBlocking, the server socket is retrieved and bound to the specified port:\n<pre class=\"brush:java\"> \nServerSocketChannel serverChannel = ServerSocketChannel.open();\nserverChannel.configureBlocking(false);\n\/\/ retrieve server socket and bind to port\nserverChannel.socket().bind(listenAddress);<\/pre>\n<p>Finally, the <code>register<\/code> method associates the selector to the socket channel.[ulp id=&#8217;lQeyBcYaL5DqTMXI&#8217;]<\/p>\n<pre class=\"brush:java\">serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);<\/pre>\n<p>The second parameter represents the type of the registration. In this case, we use <code>OP_ACCEPT<\/code>, which means the selector merely reports that a client attempts a connection to the server. Other possible options are: <code>OP_CONNECT<\/code>, which will be used by the client; <code>OP_READ<\/code>; and <code>OP_WRITE<\/code>.<br \/>\nAfter that, the <code>select<\/code> method is used on line 67, which blocks the execution and waits for events recorded on the selector in an infinite loop.<\/p>\n<pre class=\"brush:java\">this.selector.select();<\/pre>\n<\/li>\n<li>The selector waits for events and creates the keys. According to the key-types, an opportune operation is performed. There are four possible types for a key:<br \/>\n&nbsp;<\/p>\n<ul>\n<li>Acceptable: the associated client requests a connection.<\/li>\n<li>Connectable: the server accepted the connection.<\/li>\n<li>Readable: the server can read.<\/li>\n<li>Writeable: the server can write.<\/li>\n<\/ul>\n<\/li>\n<li>If an acceptable key is found, the <code>accept(SelectionKey key)<\/code> on line 93 is invoked in order to create a channel which accepts this connection, creates a standard java socket on line 97 and register the channel&nbsp;with the selector:\n<pre class=\"brush:java\">ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();\nSocketChannel channel = serverChannel.accept();\nchannel.configureBlocking(false);\nSocket socket = channel.socket();\nSocketAddress remoteAddr = socket.getRemoteSocketAddress();<\/pre>\n<\/li>\n<li>After receiving a readable key from the client, the&nbsp;<code>read(SelectionKey key)<\/code> is called on line 107 which reads from the socket channel. A byte buffer is allocated for&nbsp;reading from the channel\n<pre class=\"brush:java\">numRead = channel.read(buffer);<\/pre>\n<p>and the client&#8217;s transmitted data are echoed on System.out:<\/p>\n<pre class=\"brush:java\">System.out.println(\"Got: \" + new String(data));<\/pre>\n<\/li>\n<\/ul>\n<h3>3.2. The Client code<\/h3>\n<pre class=\"brush:java\">import java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.SocketChannel;\n\npublic class SocketClientExample {\n \n    public void startClient()\n            throws IOException, InterruptedException {\n \n        InetSocketAddress hostAddress = new InetSocketAddress(\"localhost\", 8090);\n        SocketChannel client = SocketChannel.open(hostAddress);\n \n        System.out.println(\"Client... started\");\n        \n        String threadName = Thread.currentThread().getName();\n \n        \/\/ Send messages to server\n        String [] messages = new String [] \n        \t\t{threadName + \": test1\",threadName + \": test2\",threadName + \": test3\"};\n \n        for (int i = 0; i &lt; messages.length; i++) {\n            byte [] message = new String(messages [i]).getBytes();\n            ByteBuffer buffer = ByteBuffer.wrap(message);\n            client.write(buffer);\n            System.out.println(messages [i]);\n            buffer.clear();\n            Thread.sleep(5000);\n        }\n        client.close();            \n    }\n}<\/pre>\n<ul>\n<li>In the above client code, each client thread creates a socket channel on the server&#8217;s host address on line 12:\n<pre class=\"brush:java\">SocketChannel client = SocketChannel.open(hostAddress);<\/pre>\n<\/li>\n<li>On line 19, a String array is created to be transmitted to the server using the previously created socket. The data contain also each thread&#8217;s name for distinguishing the sender:\n<pre class=\"brush:java\">String threadName = Thread.currentThread().getName();\n\/\/ Send messages to server\nString [] messages = new String [] \n{threadName + \": test1\",threadName + \": test2\",threadName + \": test3\"};<\/pre>\n<\/li>\n<li>For each string message a buffer is created on line 24:\n<pre class=\"brush:java\">ByteBuffer buffer = ByteBuffer.wrap(message);<\/pre>\n<p>and&nbsp;each message is written to the channel from the given buffer on line 25:<\/p>\n<pre class=\"brush:java\">ByteBuffer buffer = ByteBuffer.wrap(message);<\/pre>\n<\/li>\n<\/ul>\n<h3>3.3. The output<\/h3>\n<pre class=\"brush:bash\">Server started...\nClient... started\nClient... started\nclient-A: test1\nclient-B: test1\nConnected to: \/127.0.0.1:51468\nGot: client-B: test1\nConnected to: \/127.0.0.1:51467\nGot: client-A: test1\nclient-A: test2\nclient-B: test2\nGot: client-B: test2\nGot: client-A: test2\nclient-A: test3\nclient-B: test3\nGot: client-B: test3\nGot: client-A: test3\nConnection closed by client: \/127.0.0.1:51468\nConnection closed by client: \/127.0.0.1:51467<\/pre>\n<h2>4. Download Java Source Code<\/h2>\n<p>This was an example of <code>java.nio.SocketChannel<\/code><\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <strong><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/11\/SocketExampleNio.zip\">SocketExampleNio.zip<\/a><\/strong><\/div>\n","protected":false},"excerpt":{"rendered":"<p>This article introduces the SocketChannel class and its basic usage. This class is defined in the java.nio package. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1. Standard Java sockets Socket programming involves two systems communicating with one another. In implementations prior to NIO, Java TCP client socket code is handled by &hellip;<\/p>\n","protected":false},"author":63,"featured_media":1204,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[36],"tags":[1250],"class_list":["post-28916","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-nio","tag-socketchannel"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Java Nio Socket Example - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"This article introduces the SocketChannel class and its basic usage. This class is defined in the java.nio package. &nbsp; &nbsp; &nbsp; &nbsp;\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Nio Socket Example - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"This article introduces the SocketChannel class and its basic usage. This class is defined in the java.nio package. &nbsp; &nbsp; &nbsp; &nbsp;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/\" \/>\n<meta property=\"og:site_name\" content=\"Examples Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2015-11-27T19:00:59+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-03-19T11:19:02+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Nassos Hasiotis\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Nassos Hasiotis\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/\"},\"author\":{\"name\":\"Nassos Hasiotis\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/6454a437f32c31da7f0d5708c9f74a70\"},\"headline\":\"Java Nio Socket Example\",\"datePublished\":\"2015-11-27T19:00:59+00:00\",\"dateModified\":\"2019-03-19T11:19:02+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/\"},\"wordCount\":849,\"commentCount\":2,\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"keywords\":[\"SocketChannel\"],\"articleSection\":[\"nio\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/\",\"name\":\"Java Nio Socket Example - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"datePublished\":\"2015-11-27T19:00:59+00:00\",\"dateModified\":\"2019-03-19T11:19:02+00:00\",\"description\":\"This article introduces the SocketChannel class and its basic usage. This class is defined in the java.nio package. &nbsp; &nbsp; &nbsp; &nbsp;\",\"breadcrumb\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#primaryimage\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"width\":150,\"height\":150,\"caption\":\"Bipartite Graph\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/examples.javacodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java Development\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Core Java\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"nio\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/nio\/\"},{\"@type\":\"ListItem\",\"position\":5,\"name\":\"Java Nio Socket Example\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Examples and Code Snippets\",\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/javacodegeeks\",\"https:\/\/x.com\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/6454a437f32c31da7f0d5708c9f74a70\",\"name\":\"Nassos Hasiotis\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/11\/Nassos-Hasiotis-96x96.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/11\/Nassos-Hasiotis-96x96.jpg\",\"caption\":\"Nassos Hasiotis\"},\"description\":\"Nassos has graduated from Computer Engineering and Informatics Department in the University of Patras. He also holds a Master degree in Communication and Network Systems from University of Athens. He has a 10-year work experience as a Java and C++ developer in the Telecommunication and IT industry participating in various projects. He currently works as a senior software developer in the IT sector where he is mainly involved with projects for the EU requiring extensive java skills.\",\"sameAs\":[\"http:\/\/www.javacodegeeks.com\/\"],\"url\":\"https:\/\/examples.javacodegeeks.com\/author\/nassos-hasiotis\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Nio Socket Example - Java Code Geeks","description":"This article introduces the SocketChannel class and its basic usage. This class is defined in the java.nio package. &nbsp; &nbsp; &nbsp; &nbsp;","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/","og_locale":"en_US","og_type":"article","og_title":"Java Nio Socket Example - Java Code Geeks","og_description":"This article introduces the SocketChannel class and its basic usage. This class is defined in the java.nio package. &nbsp; &nbsp; &nbsp; &nbsp;","og_url":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/","og_site_name":"Examples Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2015-11-27T19:00:59+00:00","article_modified_time":"2019-03-19T11:19:02+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","type":"image\/jpeg"}],"author":"Nassos Hasiotis","twitter_card":"summary_large_image","twitter_creator":"@javacodegeeks","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Nassos Hasiotis","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#article","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/"},"author":{"name":"Nassos Hasiotis","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/6454a437f32c31da7f0d5708c9f74a70"},"headline":"Java Nio Socket Example","datePublished":"2015-11-27T19:00:59+00:00","dateModified":"2019-03-19T11:19:02+00:00","mainEntityOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/"},"wordCount":849,"commentCount":2,"publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","keywords":["SocketChannel"],"articleSection":["nio"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/","url":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/","name":"Java Nio Socket Example - Java Code Geeks","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#primaryimage"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","datePublished":"2015-11-27T19:00:59+00:00","dateModified":"2019-03-19T11:19:02+00:00","description":"This article introduces the SocketChannel class and its basic usage. This class is defined in the java.nio package. &nbsp; &nbsp; &nbsp; &nbsp;","breadcrumb":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#primaryimage","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/nio\/java-nio-socket-example\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/examples.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"},{"@type":"ListItem","position":4,"name":"nio","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/nio\/"},{"@type":"ListItem","position":5,"name":"Java Nio Socket Example"}]},{"@type":"WebSite","@id":"https:\/\/examples.javacodegeeks.com\/#website","url":"https:\/\/examples.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/examples.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/examples.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/6454a437f32c31da7f0d5708c9f74a70","name":"Nassos Hasiotis","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/11\/Nassos-Hasiotis-96x96.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/11\/Nassos-Hasiotis-96x96.jpg","caption":"Nassos Hasiotis"},"description":"Nassos has graduated from Computer Engineering and Informatics Department in the University of Patras. He also holds a Master degree in Communication and Network Systems from University of Athens. He has a 10-year work experience as a Java and C++ developer in the Telecommunication and IT industry participating in various projects. He currently works as a senior software developer in the IT sector where he is mainly involved with projects for the EU requiring extensive java skills.","sameAs":["http:\/\/www.javacodegeeks.com\/"],"url":"https:\/\/examples.javacodegeeks.com\/author\/nassos-hasiotis\/"}]}},"_links":{"self":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/28916","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/users\/63"}],"replies":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=28916"}],"version-history":[{"count":0,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/28916\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media\/1204"}],"wp:attachment":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=28916"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=28916"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=28916"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}