最近用到网络编程方面的知识,在网上看到帖子 Java Nio的Socket服务端编写 ,想跑一下提供的代码,但是在 Eclipse 中创建了对应的类,把代码粘贴进去却发现少了一个接口 TCPProtocol 的定义。
代码如下:
import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.Date; public class TCPProtocolImpl implements TCPProtocol { private int bufferSize; public TCPProtocolImpl(int bufferSize) { this.bufferSize = bufferSize; } /* * (non-Javadoc) * * @see com.weixiao.network.TCPProtocol#handleAccept(java.nio.channels. * SelectionKey) */ @Override public void handleAccept(SelectionKey key) throws IOException { SocketChannel clientChannel = ((ServerSocketChannel) key.channel()).accept(); clientChannel.configureBlocking(false); clientChannel.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize)); } /* * (non-Javadoc) * * @see com.weixiao.network.TCPProtocol#handleRead(java.nio.channels. * SelectionKey) */ @Override public void handleRead(SelectionKey key) throws IOException { // 获得与客户端通信的信道 SocketChannel clientChannel = (SocketChannel) key.channel(); // 得到并清空缓冲区 ByteBuffer buffer = (ByteBuffer) key.attachment(); buffer.clear(); // 读取信息获得读取的字节数 long bytesRead = clientChannel.read(buffer); if (bytesRead == -1) { // 没有读取到内容的情况 clientChannel.close(); } else { // 将缓冲区准备为数据传出状态 buffer.flip(); // 将字节转化为为UTF-16的字符串 String receivedString = Charset.forName("UTF-16").newDecoder().decode(buffer).toString(); // 控制台打印出来 System.out.println("接收到来自" + clientChannel.socket().getRemoteSocketAddress() + "的信息:" + receivedString); // 准备发送的文本 String sendString = "你好,客户端. @" + new Date().toString() + ",已经收到你的信息" + receivedString; buffer = ByteBuffer.wrap(sendString.getBytes("UTF-16")); clientChannel.write(buffer); // 设置为下一次读取或是写入做准备 key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } } /* * (non-Javadoc) * * @see com.weixiao.network.TCPProtocol#handleWrite(java.nio.channels. * SelectionKey) */ @Override public void handleWrite(SelectionKey key) throws IOException { // do nothing } }怎么办呢?
我们可以使用Eclipse中提供的Refactor(重构)工具提取接口,操作方法如下图:
单击鼠标右键》Refactor(重构)》Extract Interface(提取接口)
就会自动生成接口文件,代码如下:
import java.io.IOException; import java.nio.channels.SelectionKey; public interface TCPProtocol { void handleAccept(SelectionKey key) throws IOException; void handleRead(SelectionKey key) throws IOException; void handleWrite(SelectionKey key) throws IOException; }会用这个功能了, Refactor(重构)菜单的其它几个功能是不是也一并 Get 了呢?