简介
Socket和SocketChannel类封装点对点、有序的网络连接,类似于我们所熟知并喜爱的TCP/IP网络连接。
SocketChannel扮演客户端发起同一个监听服务器的连接。直到连接成功,它才能收到数据并且只会从连接到的地址接收
API
Paste_Image.pngopen():创建一个socket channel
bind():绑定某个ip:port,见于server端
socket():获取这个channel关联的socket
connect():连接某个ip:port,见于client端
isConnected():是否连接上
isConnectionPending():是否在连接中
finishConnect():
非阻塞时,用了connect方法之后,一定要用finishConnect完成连接的建立
如果连接上了就返回true,否则根据IO是block或者non-block模式来
from https://docs.oracle.com/javase/7/docs/api/java/nio/channels/SocketChannel.html
If this channel is already connected then this method will not block and will immediately return true.
If this channel is in non-blocking mode then this method will return false if the connection process is not yet complete.
If this channel is in blocking mode then this method will block until the connection either completes or fails, and will always either return true or throw a checked exception describing the failure.
常见步骤
这是针对client端的
open方法创建channel
connect方法创建连接
finishConnect方法完成连接
读写操作
具体可以参照下面demo
demo
这个可以作为client端的例子,
对应server的例子见 http://www.jianshu.com/p/a1bb8ab32245
package nio;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
public class LearnSocketChannel {
public static void main(String[] args) throws Exception {
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(new InetSocketAddress("127.0.0.1", 9999));
while (!sc.finishConnect()) {
Thread.sleep(1000);
}
System.out.println("connected\n ");
sc.close();
}
}
备注
demo说明
例子中,如果server没有开
这个client执行connect后,finishConnect会一直返回false
这也是non-block,因为期间他可以干别的事情,只不过代码里就是睡了1s
finishConnect和isConnected区别 以及 finishConnect与connect联系
finishConnect和connect是互相同步的,最终会设置state = ST_CONNECTED;
如果connect没有立刻返回true的话,必须只有finishConnect才能使得state = ST_CONNECTED;
finishConnect和isConnected区别
finishConnect促成了连接的建立
而isConnected仅仅判断state == ST_CONNECTED
返回结果上来说,两者的意义差不多,只不过finishConnect会抛异常
bind和connect的区别是什么
http://stackoverflow.com/questions/27014955/socket-connect-vs-bind
是server和client的socket通信流程决定的不同步骤
server用bind而client用connect
感觉要再去看看socket编程
refer
http://blog.csdn.net/anders_zhuo/article/details/8546604
https://docs.oracle.com/javase/8/docs/api/java/nio/channels/SocketChannel.html
http://ifeve.com/socket-channel/
(实现类源码)http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/sun/nio/ch/SocketChannelImpl.java
http://shift-alt-ctrl.iteye.com/blog/1840409
(bind和connect区别)http://stackoverflow.com/questions/27014955/socket-connect-vs-bind
网友评论