新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
JavaNIO(異步IO)Socket通信例子
服務(wù)器代碼:

10年積累的做網(wǎng)站、成都做網(wǎng)站經(jīng)驗,可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識你,你也不認(rèn)識我。但先網(wǎng)站設(shè)計后付款的網(wǎng)站建設(shè)流程,更有虹口免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
- 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
selectionKeys=selector.selectedKeys(); - Iterator
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("接收數(shù)據(jù): "+new String(b));
- echoBuffer.flip();
- sc.write(echoBuffer);
- System.out.println("返回數(shù)據(jù): "+new String(b));
- }
- }
- sc.close();
- System.out.println("連接結(jié)束");
- 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ā)送數(shù)據(jù): "+new String(buffer.array()));
- while(true)
- {
- buffer.flip();
- int i=client.read(buffer);
- if(i>0)
- {
- byte[] b=buffer.array();
- System.out.println("接收數(shù)據(jù): "+new String(b));
- client.close();
- System.out.println("連接關(guān)閉!");
- break;
- }
- }
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
本文題目:JavaNIO(異步IO)Socket通信例子
標(biāo)題鏈接:http://www.dlmjj.cn/article/coiodpp.html


咨詢
建站咨詢
