Java NIO UDP

此处不是讲述Java NIO UDP使用,而是发现网上搜到的一段代码的bug:

if ( sk.isReadable ()) {
DatagramChannel datagramChannel = ( DatagramChannel ) sk
.channel () ;
SocketAddress sa = datagramChannel
.receive ( byteBuffer ) ;
byteBuffer.flip () ;

// 测试:通过将收到的ByteBuffer首先通过缺省的编码解码成CharBuffer 再输出
CharBuffer charBuffer = Charset.defaultCharset ()
.decode ( byteBuffer ) ;
System.out.println ( "receive message:"
+ charBuffer.toString ()) ;
byteBuffer.clear () ;

String echo = "This is the reply message from 服务器。" ;
ByteBuffer buffer = Charset.defaultCharset ()
.encode ( echo ) ;
datagramChannel.write ( buffer ) ;  //Should be datagramChannel.send( buffer,sa )
}

此段代码是服务器端读取客户端发来的数据并返回信息,红色部分本是进行回送的代码,但是直接运行总是提示NotYetConnected Exception,实际上这里是TCP进行回送的函数,UDP处理发送的函数原型是send(byteBuffer, InetAddress)

你可能感兴趣的:(Java NIO UDP)