MyChange类功能是监听8821端口,接收C发过来的请求,然后把请求的字符串打印处理出现ClassCastException异常.
一下是我的源代码
异常信息
java.lang.ClassCastException: sun.nio.ch.ServerSocketChannelImpl cannot be cast to java.nio.channels.SocketChannel
at com.socket.nio.MyChange.DealwithData(MyChange.java:67)
at com.socket.nio.MyChange.run(MyChange.java:54)
at com.socket.nio.MyChange.main(MyChange.java:84)Java 代码:package com.socket.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.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;public class MyChange implements Runnable
{
 private static int port=8821;
 private ByteBuffer r_buff = ByteBuffer.allocate(1024);

 public MyChange(){
 new Thread().start();
 }
 
 @Override
public void run()
{
try{
//生成一个监听端口
ServerSocketChannel ssc=ServerSocketChannel.open();
//将侦听端设为异步方式
ssc.configureBlocking(false);
//生成一个信号监视器
Selector s=Selector.open();
//侦听端绑定到一个端口
ssc.socket().bind(new InetSocketAddress(port));
//设置侦听端所选的异步信号OP_ACCEPT
ssc.register(s, SelectionKey.OP_ACCEPT);
System.out.println("___________________");
debug("准备接收请求");
while(true){
int n=s.select();
if(n==0){////没有指定的I/O事件发生就继续
continue;
}
Iterator is=s.selectedKeys().iterator();
while(is.hasNext()){
SelectionKey key=(SelectionKey)is.next();
if(key.isAcceptable()){//侦听端信号触发
ServerSocketChannel server=(ServerSocketChannel)key.channel();
//接受一个新的连接
SocketChannel sc=server.accept();
sc.configureBlocking(false);
//设置该socket的异步信号OP_READ:当socket可读时, 
sc.register(s, SelectionKey.OP_READ);
}
if(key.isAcceptable()){//某socket可读信号
DealwithData(key);
}
is.remove();
}
}
}catch(Exception e){
e.printStackTrace();
}
}
 
 public void DealwithData(SelectionKey key) throws IOException{
 int count;
//由key获取指定socketchannel的引用
 SocketChannel sc = (SocketChannel)key.channel();
 r_buff.clear();//清空buffer
//读取数据到r_buff
 while((count=sc.read(r_buff))>0);
 //确保r_buff可读
 r_buff.flip();
 byte[] temp=new byte[r_buff.limit()];
 r_buff.get(temp);
 System.out.println("接收到的数据是"+new String(temp));
 r_buff.clear();
 }
 
 private static void debug(String s)
{
System.out.println(s);
}
 public static void main(String args[]){
 new MyChange().run();
 }
}