java

位置:IT落伍者 >> java >> 浏览文章

Java NIO(异步IO)Socket通信例子


发布日期:2023年10月22日
 
Java NIO(异步IO)Socket通信例子

//Java NIO (异步IO)Socket通信例子:

服务器代码:

import *;

import javanio*;

import javaniochannels*;

import javautil*;

public class server

{

ServerSocketChannel ssc ;

public void start()

{

try

{

Selector selector = Selectoropen();

ServerSocketChannel ssc=ServerSocketChannelopen();

nfigureBlocking(false);

ServerSocket ss=sscsocket();

InetSocketAddress address = new InetSocketAddress();

ssbind(address);

sscregister(selector SelectionKeyOP_ACCEPT);

Systemoutprintln(端口注册完毕!);

while(true)

{

selectorselect();

Set<SelectionKey> selectionKeys=selectorselectedKeys();

Iterator<SelectionKey> iter=erator();

ByteBuffer echoBuffer=ByteBufferallocate();

SocketChannel sc;

while(iterhasNext())

{

SelectionKey key=iternext();

if((keyreadyOps()&SelectionKeyOP_ACCEPT)==SelectionKeyOP_ACCEPT)

{

ServerSocketChannel subssc=(ServerSocketChannel)keychannel();

sc=subsscaccept();

nfigureBlocking(false);

scregister(selector SelectionKeyOP_READ);

iterremove();

Systemoutprintln(有新连接:+sc);

}

else if((keyreadyOps()&SelectionKeyOP_READ)==SelectionKeyOP_READ)

{

sc=(SocketChannel) keychannel();

while(true)

{

echoBufferclear();

int a;

try

{

a=scread(echoBuffer);

}

catch(Exception e)

{

eprintStackTrace();

break;

}

if(a==) break;

if(a>)

{

byte[] b=echoBufferarray();

Systemoutprintln(接收数据: +new String(b));

echoBufferflip();

scwrite(echoBuffer);

Systemoutprintln(返回数据: +new String(b));

}

}

scclose();

Systemoutprintln(连接结束);

Systemoutprintln(=============================);

iterremove();

}

}

}

}

catch (Exception e)

{

eprintStackTrace();

}

}

}

客户端代码:

import *;

import javanio*;

import javaniochannels*;

public class client

{

public void start()

{

try

{

SocketAddress address = new InetSocketAddress(localhost);

SocketChannel client=SocketChannelopen(address);

nfigureBlocking(false);

String a=asdasdasdasddffasfas;

ByteBuffer buffer=ByteBufferallocate();

bufferput(agetBytes());

bufferclear();

int d=clientwrite(buffer);

Systemoutprintln(发送数据: +new String(bufferarray()));

while(true)

{

bufferflip();

int i=clientread(buffer);

if(i>)

{

byte[] b=bufferarray();

Systemoutprintln(接收数据: +new String(b));

clientclose();

Systemoutprintln(连接关闭!);

break;

}

}

}

catch(Exception e)

{

eprintStackTrace();

}

}

}

               

上一篇:java中super的两种用法

下一篇:JAVA文件操作类,方便读写小文件