2010年2月5日
#
下面这段话来自http://dreava.javaeye.com/blog/546005
所谓高手,就是说他在模仿的过程中不断比较自己写的东西和框架本身的差异,不断发现问题,想尽办法解决问题,思考得越多,你碰到的问题就会越多,这是一个
正向循环,最终你的技术能力就会螺旋式的上升;而低手只会被动的等待问题,一旦问题自己觉得解决得差不多就放下了,这样自然就不会产生更多的问题,最终技
术能力就始终停留在那个菜鸟阶段。
我们只有生活一次的机会:人需要勇敢的过他的生活,过的清醒,过的美。人要做强有力的,独立的,高尚的人物;人要创造历史,免得叫后代人有权利批评我们。
2010年2月4日
#
ByteBuffer用法小结(未完待续)
在NIO中,数据的读写操作始终是与缓冲区相关联的.读取时信道(SocketChannel)将数据读入缓冲区,写入时首先要将发送的数据按顺序填入缓冲区.缓冲区是定长的,基本上它只是一个列表,它的所有元素都是基本数据类型.ByteBuffer是最常用的缓冲区,它提供了读写其他数据类型的方法,且信道的读写方法只接收ByteBuffer.因此ByteBuffer的用法是有必要牢固掌握的.
1.创建ByteBuffer
1.1 使用allocate()静态方法
ByteBuffer buffer=ByteBuffer.allocate(256);
以上方法将创建一个容量为256字节的ByteBuffer,如果发现创建的缓冲区容量太小,唯一的选择就是重新创建一个大小合适的缓冲区.
1.2 通过包装一个已有的数组来创建
如下,通过包装的方法创建的缓冲区保留了被包装数组内保存的数据.
ByteBuffer buffer=ByteBuffer.wrap(byteArray);
如果要将一个字符串存入ByteBuffer,可以如下操作:
String sendString="你好,服务器. ";
ByteBuffer sendBuffer=ByteBuffer.wrap(sendString.getBytes("UTF-16"));
2.回绕缓冲区
buffer.flip();
这个方法用来将缓冲区准备为数据传出状态,执行以上方法后,输出通道会从数据的开头而不是末尾开始.回绕保持缓冲区中的数据不变,只是准备写入而不是读取.
3.清除缓冲区
buffer.clear();
这个方法实际上也不会改变缓冲区的数据,而只是简单的重置了缓冲区的主要索引值.不必为了每次读写都创建新的缓冲区,那样做会降低性能.相反,要重用现在的缓冲区,在再次读取之前要清除缓冲区.
4.从套接字通道(信道)读取数据
int bytesReaded=socketChannel.read(buffer);
执行以上方法后,通道会从socket读取的数据填充此缓冲区,它返回成功读取并存储在缓冲区的字节数.在默认情况下,这至少会读取一个字节,或者返回-1指示数据结束.
5.向套接字通道(信道)写入数据
socketChannel.write(buffer);
此方法以一个ByteBuffer为参数,试图将该缓冲区中剩余的字节写入信道.
作为技术人员就当如此,先潜心把技术钻研好,当能够某个领域首屈一指的专家,人们在接触这个领域就会想到你的时候,其它也就纷至沓来了;而反过来是舍本逐末的做法,不值得提倡。
2010年2月3日
#
这只是长征路上的一小步,以后还有待改进。
NIO Selector示意图:
客户端代码:
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;
/**
* NIO TCP 客户端
*
* @date 2010-2-3
* @time 下午03:33:26
* @version 1.00
*/
public class TCPClient{
// 信道选择器
private Selector selector;
// 与服务器通信的信道
SocketChannel socketChannel;
// 要连接的服务器Ip地址
private String hostIp;
// 要连接的远程服务器在监听的端口
private int hostListenningPort;
/**
* 构造函数
* @param HostIp
* @param HostListenningPort
* @throws IOException
*/
public TCPClient(String HostIp,int HostListenningPort)throws IOException{
this.hostIp=HostIp;
this.hostListenningPort=HostListenningPort;
initialize();
}
/**
* 初始化
* @throws IOException
*/
private void initialize() throws IOException{
// 打开监听信道并设置为非阻塞模式
socketChannel=SocketChannel.open(new InetSocketAddress(hostIp, hostListenningPort));
socketChannel.configureBlocking(false);
// 打开并注册选择器到信道
selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_READ);
// 启动读取线程
new TCPClientReadThread(selector);
}
/**
* 发送字符串到服务器
* @param message
* @throws IOException
*/
public void sendMsg(String message) throws IOException{
ByteBuffer writeBuffer=ByteBuffer.wrap(message.getBytes("UTF-16"));
socketChannel.write(writeBuffer);
}
public static void main(String[] args) throws IOException{
TCPClient client=new TCPClient("192.168.0.1",1978);
client.sendMsg("你好!Nio!醉里挑灯看剑,梦回吹角连营");
}
}
客户端读取线程代码:
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
public class TCPClientReadThread implements Runnable{
private Selector selector;
public TCPClientReadThread(Selector selector){
this.selector=selector;
new Thread(this).start();
}
public void run() {
try {
while (selector.select() > 0) {
// 遍历每个有可用IO操作Channel对应的SelectionKey
for (SelectionKey sk : selector.selectedKeys()) {
// 如果该SelectionKey对应的Channel中有可读的数据
if (sk.isReadable()) {
// 使用NIO读取Channel中的数据
SocketChannel sc = (SocketChannel) sk.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
sc.read(buffer);
buffer.flip();
// 将字节转化为为UTF-16的字符串
String receivedString=Charset.forName("UTF-16").newDecoder().decode(buffer).toString();
// 控制台打印出来
System.out.println("接收到来自服务器"+sc.socket().getRemoteSocketAddress()+"的信息:"+receivedString);
// 为下一次读取作准备
sk.interestOps(SelectionKey.OP_READ);
}
// 删除正在处理的SelectionKey
selector.selectedKeys().remove(sk);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
服务器端代码:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
/**
* TCP服务器端
*
* @date 2010-2-3
* @time 上午08:39:48
* @version 1.00
*/
public class TCPServer{
// 缓冲区大小
private static final int BufferSize=1024;
// 超时时间,单位毫秒
private static final int TimeOut=3000;
// 本地监听端口
private static final int ListenPort=1978;
public static void main(String[] args) throws IOException{
// 创建选择器
Selector selector=Selector.open();
// 打开监听信道
ServerSocketChannel listenerChannel=ServerSocketChannel.open();
// 与本地端口绑定
listenerChannel.socket().bind(new InetSocketAddress(ListenPort));
// 设置为非阻塞模式
listenerChannel.configureBlocking(false);
// 将选择器绑定到监听信道,只有非阻塞信道才可以注册选择器.并在注册过程中指出该信道可以进行Accept操作
listenerChannel.register(selector, SelectionKey.OP_ACCEPT);
// 创建一个处理协议的实现类,由它来具体操作
TCPProtocol protocol=new TCPProtocolImpl(BufferSize);
// 反复循环,等待IO
while(true){
// 等待某信道就绪(或超时)
if(selector.select(TimeOut)==0){
System.out.print("独自等待.");
continue;
}
// 取得迭代器.selectedKeys()中包含了每个准备好某一I/O操作的信道的SelectionKey
Iterator<SelectionKey> keyIter=selector.selectedKeys().iterator();
while(keyIter.hasNext()){
SelectionKey key=keyIter.next();
try{
if(key.isAcceptable()){
// 有客户端连接请求时
protocol.handleAccept(key);
}
if(key.isReadable()){
// 从客户端读取数据
protocol.handleRead(key);
}
if(key.isValid() && key.isWritable()){
// 客户端可写时
protocol.handleWrite(key);
}
}
catch(IOException ex){
// 出现IO异常(如客户端断开连接)时移除处理过的键
keyIter.remove();
continue;
}
// 移除处理过的键
keyIter.remove();
}
}
}
}
协议接口代码:
import java.io.IOException;
import java.nio.channels.SelectionKey;
/**
* TCPServerSelector与特定协议间通信的接口
*
* @date 2010-2-3
* @time 上午08:42:42
* @version 1.00
*/
public interface TCPProtocol{
/**
* 接收一个SocketChannel的处理
* @param key
* @throws IOException
*/
void handleAccept(SelectionKey key) throws IOException;
/**
* 从一个SocketChannel读取信息的处理
* @param key
* @throws IOException
*/
void handleRead(SelectionKey key) throws IOException;
/**
* 向一个SocketChannel写入信息的处理
* @param key
* @throws IOException
*/
void handleWrite(SelectionKey key) throws IOException;
}
协议实现类代码:
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;
/**
* TCPProtocol的实现类
*
* @date 2010-2-3
* @time 上午08:58:59
* @version 1.00
*/
public class TCPProtocolImpl implements TCPProtocol{
private int bufferSize;
public TCPProtocolImpl(int bufferSize){
this.bufferSize=bufferSize;
}
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));
}
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);
}
}
public void handleWrite(SelectionKey key) throws IOException {
// do nothing
}
}
2010年2月2日
#
改成了多线程处理,其余和原来差不多。
服务器端代码:
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
/**
* UDP服务器端
* @author Administrator
*
*/
public class UDPServer{
public static void main(String[] args) throws Exception{
// 使用DatagramChannel的open工厂方法创建一个数据报信道实例,该实例未绑定
DatagramChannel channel=DatagramChannel.open();
// 将该数据报信道实例的底层套接字绑定到5000端口
channel.socket().bind(new InetSocketAddress(5000));
// 使用ByteBuffer的静态方法创建一个新缓冲区,最长接收为60字节的数据报文
ByteBuffer bf=ByteBuffer.allocate(60);
while(true){
System.out.println("监听开始
");
// 将接收到的数据报文存入指定的缓冲区并返回发送者的地址,如果缓冲区的剩余空间小于数据报文中的数据大小,多余的数据将毫无提示的丢失
SocketAddress remoteAddress=channel.receive(bf);
// 使用一个线程获得和返回信息
new ProcessClientRequestThread(channel,remoteAddress,bf);
}
}
}
服务器端处理客户端请求代码:
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;
/**
* 服务器端处理客户端请求的线程
* @author Administrator
*
*/
public class ProcessClientRequestThread implements Runnable{
// 监听的数据报信道
private DatagramChannel channel;
// 连接过来的远程服务器
private SocketAddress remoteAddress;
// 获取信息的缓冲区
private ByteBuffer bf;
/**
* 构造函数
* @param channel
* @param remoteAddress
* @param bf
*/
public ProcessClientRequestThread(DatagramChannel channel,SocketAddress remoteAddress,ByteBuffer bf){
this.channel=channel;
this.remoteAddress=remoteAddress;
this.bf=bf;
new Thread(this).start();
}
@Override
public void run() {
try{
System.out.println("收到了客户端的请求.");
/********************************************
* 接收部分
********************************************/
// 反转此缓冲区,为下次读取做准备
bf.flip();
// 将字节转化为为UTF-16的字符串
String receivedString=Charset.forName("UTF-16").newDecoder().decode(bf).toString();
// 控制台打印出来
System.out.println("接收到来自客户端"+remoteAddress.toString()+"的信息:"+receivedString);
/********************************************
* 发送部分
********************************************/
// 将信息回执发送回去
String sendString="你好,客户端("+remoteAddress.toString()+") 我已收到你的来信.";
ByteBuffer bfSend=ByteBuffer.wrap(sendString.getBytes("UTF-16"));
channel.send(bfSend, remoteAddress);
System.out.println("处理客户端的请求完毕.");
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
服务器端输出:
监听开始
收到了客户端的请求.
接收到来自客户端/192.168.1.107:55909的信息:你好,服务器. @Tue Feb 02 13:44:07
处理客户端的请求完毕.
客户端代码:
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;
import java.util.Date;
/**
* UDP客户端
* @author Administrator
*
*/
public class UDPClient{
public static void main(String[] args) throws Exception{
/********************************************
* 发送部分
********************************************/
// 使用DatagramChannel的open工厂方法创建一个数据报信道实例,该实例未绑定
DatagramChannel channel=DatagramChannel.open();
// 准备发送的文本
String sendString="你好,服务器. @"+new Date().toString();
// 将要发送的文本进行编码后置入一个缓冲区中
ByteBuffer sendBuffer=ByteBuffer.wrap(sendString.getBytes("UTF-16"));
// 创建一个包含了给定缓冲区中的中的数据的数据报文,并将其发送到目的地址指定的SocketAddress上
channel.send(sendBuffer, new InetSocketAddress("192.168.1.107",5000));
System.out.println("向服务器发送信息完毕");
/********************************************
* 接收部分
********************************************/
// 使用ByteBuffer的静态方法创建一个新缓冲区,最长接收为80字节的数据报文
ByteBuffer receiveBuffer=ByteBuffer.allocate(80);
// 收取服务器端返回的信息
SocketAddress remoteAddress=channel.receive(receiveBuffer);
receiveBuffer.flip();
// 将字节转化为为UTF-16的字符串
String receivedString=Charset.forName("UTF-16").newDecoder().decode(receiveBuffer).toString();
// 控制台打印出来
System.out.println("接收到来自服务器"+remoteAddress.toString()+"的信息:"+receivedString);
}
}
客户端输出:
向服务器发送信息完毕
接收到来自服务器/192.168.1.107:5000的信息:你好,客户端(/192.168.1.107:55912) 我已收到你的来信.
2010年2月1日
#