• Post Reply Bookmark Topic Watch Topic
  • New Topic

Nonblocking socket question of client'sprogram ,help!!!!!!

 
jgm jinggm
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nonblocking socket client'sprogram like this:
SocketChannel m_oCltChannel = null;
Selector m_oReadSelector = null;
Selector m_oWriteSelector = null;
m_oReadSelector = Selector.open();
m_oWriteSelector = Selector.open();
m_oCltChannel = SocketChannel.open();
m_oCltChannel.configureBlocking(false);
InetSocketAddress isa = new InetSocketAddress(m_sServerHost, m_iPort);
m_oCltChannel.connect(isa);
m_oCltChannel.register(m_oReadSelector,SelectionKey.OP_CONNECT | SelectionKey.OP_READ );
m_oClt.m_oCltChannel.register(m_oWriteSelector,SelectionKey.OP_WRITE );
while(true){
if(m_oReadSelector.select()>0){
Set oReadKeys = m_oReadSelector.selectedKeys();
Iterator i = oReadKeys.iterator();
while(i.hasNext()){
SelectionKey tmp = (SelectionKey)i.next();
i.remove();
if (tmp.isConnectable()){
/*why come here always ???*/
if (((SocketChannel)tmp.channel()).isConnectionPending()){
while(!((SocketChannel)tmp.channel()).finishConnecta(){}
}
if (tmp.isReadable()){
/*why dont come here always ???*/
}
}
}
if(m_oWriteSelector.select()>0){
Set oWriteKeys = m_oWriteSelector.selectedKeys();
Iterator i = oWriteKeys.iterator();
while(i.hasNext()){
SelectionKey tmp = (SelectionKey)i.next();
i.remove();
if (tmp.isWriteable()){
/*why dont come here always ???*/
}
}
}
}
if i use blocking socket, this while do well work .what happend???
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to the I/O forum.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the future, please indent your code, and use [code] tags to display the code on this forum. Making your code readable will help encourage others to look at it, which increases the chance someone will answer your question.
Looking at your code I see a couple possibilities:
(1) The isReadable() is only evaluated when isConnectable() is true. So you can only read if the key indicates that the channel is both connectable and readable at the same time. What if there's a delay - e.g., when you connect, the server still has to write something before you can read it. So maybe yoiu have one even where isConnectable() is true, then later one or more events where isReadable() is true (but not isConnectable(), because you've already connected). You miss these because of your block structure.
(2) I'm not sure what your "finishConnecta()" method is doing; there are too many typos in that area, and the code doesn't parse.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!