SocketChannel 例子
这几天在看mina
mina 基于socketChannel 和 DatagramChannel 建立的无阻塞链接。
所以就看了看socket channel 的使用方式,做一份备忘吧。
socketChannel 的使用方式
server端
package com.jimmy.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
public class TestServerSocketChannel {
public static void main(String[] args) throws IOException {
int port=37;
ByteBuffer in=ByteBuffer.allocate(4);
ByteBuffer out=ByteBuffer.allocate(8);
//设置绑定端口
SocketAddress address=new InetSocketAddress(port);
//Opens a server-socket channel.
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
//Binds the ServerSocket to a specific address (IP address and port number).
serverSocketChannel.socket().bind(address);
System.err.println("bound to " + address);
//Accepts a connection made to this channel's socket
SocketChannel channel=serverSocketChannel.accept();
if(channel == null) {
return;
}
//clear byte buffer
in.clear();
//read byte to "in" buffer
channel.read(in);
//Flips this buffer
in.flip();
int a=in.getInt();
System.out.println("a:" + a);
//get remote socket address
SocketAddress client=channel.socket().getRemoteSocketAddress();
System.err.println(client);
long secondsSince1970=System.currentTimeMillis();
//clear "out" byte buffer
out.clear();
//put currentTimeMillis value into "out" byte buffer
out.putLong(secondsSince1970);
//Flips this buffer
out.flip();
//Writes a sequence of bytes to this channel from the given buffer
//write data from position to limit of buffer
//so before write ,buffer need call flip method
channel.write(out);
channel.close();
serverSocketChannel.close();
}
}
client 端
package com.jimmy.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Date;
public class TestClientSocketChannel {
public static void main(String[] args) throws IOException {
int port=37;
SocketChannel channel=SocketChannel.open();
SocketAddress server=new InetSocketAddress("192.168.1.79", port);
channel.connect(server);
ByteBuffer buffer=ByteBuffer.allocate(4);
ByteBuffer readBuffer=ByteBuffer.allocate(8);
// send a byte of data to the server
buffer.putInt(100);
buffer.flip();
channel.write(buffer);
// get the buffer ready to receive data
channel.read(readBuffer);
readBuffer.flip();
// convert seconds since 1900 to a java.util.Date
long currentTimeMillis=readBuffer.getLong();
Date time=new Date(currentTimeMillis);
System.out.println(time);
channel.close();
}
}
socket channel 操作的对象是ByteBuffer
在read的时候如果byte length 超过了 byteBuffer分配的空间 会抛出java.nio.BufferUnderflowException 异常。
在设置 bytebuffer 空间的时候建议设置大一些。