服务器代码:
10年积累的做网站、成都做网站经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站设计后付款的网站建设流程,更有虹口免费网站建设让你可以放心的选择与我们合作。
- 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("接收数据: "+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("发送数据: "+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();
- }
- }
新闻标题:JavaNIO(异步IO)Socket通信例子
转载注明:http://www.gawzjz.com/qtweb/news25/204225.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联