创建方式:
1.打开一个SocketChannel并连接到互联网上的某台服务器。
2.一个新连接到达ServerSocketChannel时,会创建一个SocketChannel。
import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import org.junit.Test; public class SocketChannelTest { @Test public void testRead() throws Exception{ //打开 SocketChannel SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("www.baidu.com", 80)); Charset charset = Charset.forName("GBK"); socketChannel.write(charset.encode("GET " + "/ HTTP/1.1" + "\r\n\r\n")); ByteBuffer buf = ByteBuffer.allocate(48); while (socketChannel.read(buf) != -1) { buf.flip(); while(buf.hasRemaining()){ System.out.print((char)buf.get());; } buf.clear(); } //关闭 SocketChannel socketChannel.close(); } @Test public void testWrite()throws Exception{ String newData = "Hello SocketChannel " + System.currentTimeMillis(); SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("www.baidu.com", 80)); ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(newData.getBytes()); buf.flip(); while(buf.hasRemaining()) { socketChannel.write(buf); } } }