您好,登錄后才能下訂單哦!
這篇文章主要講解了“Java NIO Socket通信的方法是什么”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Java NIO Socket通信的方法是什么”吧!
服務器代碼:
import java.net.*; import java.nio.*; import java.nio.channels.*; import java.util.*; public class server { ServerSocketChannel ssc ; public void start() { try { Selector selector = Selector.open(); ServerSocketChannel ssc=ServerSocketChannel.open(); ssc.configureBlocking(false); ServerSocket ss=ssc.socket(); InetSocketAddress address = new InetSocketAddress(55555); ss.bind(address); ssc.register(selector, SelectionKey.OP_ACCEPT); System.out.println("端口注冊完畢!"); while(true) { selector.select(); Set<SelectionKey> selectionKeys=selector.selectedKeys(); Iterator<SelectionKey> iter=selectionKeys.iterator(); ByteBuffer echoBuffer=ByteBuffer.allocate(20); SocketChannel sc; while(iter.hasNext()) { SelectionKey key=iter.next(); if((key.readyOps()&SelectionKey.OP_ACCEPT)==SelectionKey.OP_ACCEPT) { ServerSocketChannel subssc=(ServerSocketChannel)key.channel(); sc=subssc.accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); iter.remove(); System.out.println("有新連接:"+sc); } else if((key.readyOps()&SelectionKey.OP_READ)==SelectionKey.OP_READ) { sc=(SocketChannel) key.channel(); while(true) { echoBuffer.clear(); int a; try { a=sc.read(echoBuffer); } catch(Exception e) { e.printStackTrace(); break; } if(a==-1) break; if(a>0) { byte[] b=echoBuffer.array(); System.out.println("接收數據: "+new String(b)); echoBuffer.flip(); sc.write(echoBuffer); System.out.println("返回數據: "+new String(b)); } } sc.close(); System.out.println("連接結束"); System.out.println("============================="); iter.remove(); } } } } catch (Exception e) { e.printStackTrace(); } } }
客戶端代碼:
import java.net.*; import java.nio.*; import java.nio.channels.*; public class client { public void start() { try { SocketAddress address = new InetSocketAddress("localhost",55555); SocketChannel client=SocketChannel.open(address); client.configureBlocking(false); String a="asdasdasdasddffasfas"; ByteBuffer buffer=ByteBuffer.allocate(20); buffer.put(a.getBytes()); buffer.clear(); int d=client.write(buffer); System.out.println("發(fā)送數據: "+new String(buffer.array())); while(true) { buffer.flip(); int i=client.read(buffer); if(i>0) { byte[] b=buffer.array(); System.out.println("接收數據: "+new String(b)); client.close(); System.out.println("連接關閉!"); break; } } } catch(Exception e) { e.printStackTrace(); } }
感謝各位的閱讀,以上就是“Java NIO Socket通信的方法是什么”的內容了,經過本文的學習后,相信大家對Java NIO Socket通信的方法是什么這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。