問題描述:
服務(wù)端已啟動,端口9999。
客戶端通過Channel方式實現(xiàn),功能一切正常。
客戶端通過Selector+Channel方式實現(xiàn),程序報錯。
哪位兄臺遇到過此問題,請賜教
Exception in thread "main" java.nio.channels.NotYetConnectedException
at sun.nio.ch.SocketChannelImpl.ensureWriteOpen(SocketChannelImpl.java:269)
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:474)
at demo.nio.SelectorDemo.run(SelectorDemo.java:55)
at demo.nio.SelectorDemo.main(SelectorDemo.java:24)
服務(wù)端代碼:
package demo.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
/**
* @ClassName: ServerSocketChannel
* @Description:
* @author
* @date 2018年1月24日 下午9:53:15
*
*/
public class ServerSocketChannelDemo implements Runnable {
public static void main(String[] args) {
ServerSocketChannelDemo serverSocketChannelDemo = new ServerSocketChannelDemo();
serverSocketChannelDemo.run();
}
public void run() {
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
serverSocketChannel.configureBlocking(false);
while(true){
SocketChannel socketChannel = serverSocketChannel.accept();
if(socketChannel != null){
//do something with socketChannel...
ByteBuffer buf1 = ByteBuffer.allocate(10000);
socketChannel.read(buf1);
buf1.flip();
if(buf1.hasRemaining())
System.out.println(">>>服務(wù)端收到數(shù)據(jù):"+new String(buf1.array()));
buf1.clear();
ByteBuffer buf2 = ByteBuffer.allocate(10000);
buf2.put("A word from server!".getBytes());
buf2.flip();
socketChannel.write(buf2);
socketChannel.close();
}else{
Thread.sleep(3000);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
客戶端代碼(Channel實現(xiàn)):
package demo.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
/**
* @ClassName: SocketChannelDemo
* @Description:
* @author
* @date 2018年1月11日 下午10:01:40
*
*/
public class SocketChannelDemo implements Runnable{
public static void main(String[] args) {
SocketChannelDemo socketChannelDemo = new SocketChannelDemo();
socketChannelDemo.run();
}
public void run() {
try {
//通道
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));
while(!socketChannel.finishConnect()){
wait(1000);
}
//緩沖區(qū)
ByteBuffer buf1 = ByteBuffer.allocate(10000);
buf1.put("A word from client!".getBytes());
buf1.flip();
if(buf1.hasRemaining())
socketChannel.write(buf1);
buf1.clear();
ByteBuffer buf2 = ByteBuffer.allocate(10000);
socketChannel.read(buf2);
if(buf2.hasRemaining())
System.out.println(">>>客戶端接收數(shù)據(jù):"+new String(buf2.array()));
buf2.clear();
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
客戶端代碼(Selector+Channel實現(xiàn)):
package demo.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;
import java.util.Iterator;
/**
* @ClassName: SelectorDemo
* @Description:
* @author
* @date 2018年1月12日 下午9:06:21
*
*/
public class SelectorDemo implements Runnable{
public static void main(String[] args) {
SelectorDemo selectorDemo = new SelectorDemo();
selectorDemo.run();
}
public void run() {
try {
//選擇器
Selector selector = Selector.open();
//通道
SocketChannel socketChannel1 = SocketChannel.open();
socketChannel1.configureBlocking(false);
SelectionKey key1 = socketChannel1.register(selector, SelectionKey.OP_CONNECT);
socketChannel1.connect(new InetSocketAddress("127.0.0.1", 9999));
while(true){
int readyChannels = selector.selectNow();//selectNow()非阻塞,select(timeout)和select()阻塞
if(readyChannels == 0)
continue;
//selector.wakeup();//第一個線程調(diào)用select后,需要執(zhí)行此方法,阻塞在select上的線程會立馬返回。
Set<?> selectedKeys = selector.selectedKeys();
Iterator<?> keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()){
SelectionKey key = (SelectionKey) keyIterator.next();
if(key.isAcceptable()){
// a connection was accepted by a ServerSocketChannel.
ServerSocketChannel socketchannel = (ServerSocketChannel) key.channel();
}else if(key.isConnectable()){
// a connection was established with a remote server.
SocketChannel socketchannel = (SocketChannel) key.channel();
ByteBuffer buf1 = ByteBuffer.allocate(10000);
buf1.put("A word from client!".getBytes());
buf1.flip();
socketchannel.write(buf1);
buf1.clear();
ByteBuffer buf2 = ByteBuffer.allocate(10000);
socketchannel.read(buf2);
buf2.flip();
System.out.println(">>>客戶端接收數(shù)據(jù):"+new String(buf2.array()));
buf2.clear();
}else if(key.isReadable()){
// a channel is ready for reading.
SelectableChannel fileChannel = key.channel();
}else if(key.isWritable()){
// a channel is ready for writing.
SelectableChannel fileChannel = key.channel();
}
keyIterator.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package demo.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;
import java.util.Iterator;
/**
* @ClassName: SelectorDemo
* @Description:
* @author
* @date 2018年1月12日 下午9:06:21
*
*/
public class SelectorDemo implements Runnable{
public static void main(String[] args) {
SelectorDemo selectorDemo = new SelectorDemo();
selectorDemo.run();
}
public void run() {
try {
//選擇器
Selector selector = Selector.open();
//通道
SocketChannel socketChannel1 = SocketChannel.open();
socketChannel1.configureBlocking(false);
SelectionKey key1 = socketChannel1.register(selector, SelectionKey.OP_CONNECT);
socketChannel1.connect(new InetSocketAddress("127.0.0.1", 9999));
while(true){
int readyChannels = selector.selectNow();//selectNow()非阻塞,select(timeout)和select()阻塞
if(readyChannels == 0)
continue;
//selector.wakeup();//第一個線程調(diào)用select后,需要執(zhí)行此方法,阻塞在select上的線程會立馬返回。
Set<?> selectedKeys = selector.selectedKeys();
Iterator<?> keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()){
SelectionKey key = (SelectionKey) keyIterator.next();
if(key.isAcceptable()){
// a connection was accepted by a ServerSocketChannel.
ServerSocketChannel socketchannel = (ServerSocketChannel) key.channel();
}else if(key.isConnectable()){
// a connection was established with a remote server, false.
//Now is Connectable(可連接,但是未必已經(jīng)連接完成)
try {
socketchannel.finishConnect();//如果是非阻塞模式,可能要循環(huán)詢問
} catch (Exception e) {}
SocketChannel socketchannel = (SocketChannel) key.channel();
ByteBuffer buf1 = ByteBuffer.allocate(10000);
buf1.put("A word from client!".getBytes());
buf1.flip();
socketchannel.write(buf1);
buf1.clear();
ByteBuffer buf2 = ByteBuffer.allocate(10000);
socketchannel.read(buf2);
buf2.flip();
System.out.println(">>>客戶端接收數(shù)據(jù):"+new String(buf2.array()));
buf2.clear();
}else if(key.isReadable()){
// a channel is ready for reading.
SelectableChannel fileChannel = key.channel();
}else if(key.isWritable()){
// a channel is ready for writing.
SelectableChannel fileChannel = key.channel();
}
keyIterator.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
題主的英文好像不錯,可以點進SocketChannel.finishConnect()方法里面看下注釋
北大青鳥APTECH成立于1999年。依托北京大學優(yōu)質(zhì)雄厚的教育資源和背景,秉承“教育改變生活”的發(fā)展理念,致力于培養(yǎng)中國IT技能型緊缺人才,是大數(shù)據(jù)專業(yè)的國家
北大青鳥中博軟件學院創(chuàng)立于2003年,作為華東區(qū)著名互聯(lián)網(wǎng)學院和江蘇省首批服務(wù)外包人才培訓基地,中博成功培育了近30000名軟件工程師走向高薪崗位,合作企業(yè)超4
中公教育集團創(chuàng)建于1999年,經(jīng)過二十年潛心發(fā)展,已由一家北大畢業(yè)生自主創(chuàng)業(yè)的信息技術(shù)與教育服務(wù)機構(gòu),發(fā)展為教育服務(wù)業(yè)的綜合性企業(yè)集團,成為集合面授教學培訓、網(wǎng)
達內(nèi)教育集團成立于2002年,是一家由留學海歸創(chuàng)辦的高端職業(yè)教育培訓機構(gòu),是中國一站式人才培養(yǎng)平臺、一站式人才輸送平臺。2014年4月3日在美國成功上市,融資1
曾工作于聯(lián)想擔任系統(tǒng)開發(fā)工程師,曾在博彥科技股份有限公司擔任項目經(jīng)理從事移動互聯(lián)網(wǎng)管理及研發(fā)工作,曾創(chuàng)辦藍懿科技有限責任公司從事總經(jīng)理職務(wù)負責iOS教學及管理工作。
浪潮集團項目經(jīng)理。精通Java與.NET 技術(shù), 熟練的跨平臺面向?qū)ο箝_發(fā)經(jīng)驗,技術(shù)功底深厚。 授課風格 授課風格清新自然、條理清晰、主次分明、重點難點突出、引人入勝。
精通HTML5和CSS3;Javascript及主流js庫,具有快速界面開發(fā)的能力,對瀏覽器兼容性、前端性能優(yōu)化等有深入理解。精通網(wǎng)頁制作和網(wǎng)頁游戲開發(fā)。
具有10 年的Java 企業(yè)應(yīng)用開發(fā)經(jīng)驗。曾經(jīng)歷任德國Software AG 技術(shù)顧問,美國Dachieve 系統(tǒng)架構(gòu)師,美國AngelEngineers Inc. 系統(tǒng)架構(gòu)師。