////////////////////////
//AsyncServer.java
// by zztudou@163.com
////////////////////////
import java.nio.channels.SocketChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.spi.SelectorProvider;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Iterator;
import java.util.LinkedList;
import java.io.IOException;
class AsyncServer implements Runnable {
private ByteBuffer r_buff = ByteBuffer.allocate(1024);
private ByteBuffer w_buff = ByteBuffer.allocate(1024);
private static int port = 8848;
public AsyncServer() {
new Thread(this).start();
}
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("echo server has been set up ......");
while (true) {
int n = s.select();
if (n == 0) {// 没有指定的I/O事件发生
continue;
}
Iterator it = s.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();
if (key.isAcceptable()) {// 侦听端信号触发
ServerSocketChannel server = (ServerSocketChannel) key
.channel();
// 接受一个新的连接
SocketChannel sc = server.accept();
sc.configureBlocking(false);
// 设置该socket的异步信号OP_READ:当socket可读时,
// 触发函数DealwithData();
sc.register(s, SelectionKey.OP_READ);
}
if (key.isReadable()) {// 某socket可读信号
DealwithData(key);
}
it.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();
// 读取数据到r_buff
while ((count = sc.read(r_buff)) > 0)
;
// 确保r_buff可读
r_buff.flip();
w_buff.clear();
// 将r_buff内容拷入w_buff
w_buff.put(r_buff);
w_buff.flip();
// 将数据返回给客户端
EchoToClient(sc);
w_buff.clear();
r_buff.clear();
}
public void EchoToClient(SocketChannel sc) throws IOException {
while (w_buff.hasRemaining())
sc.write(w_buff);
}
public static void main(String args[]) {
if (args.length > 0) {
port = Integer.parseInt(args[0]);
}
new AsyncServer();
}
}
java网络游戏服务器端测试
2星 需积分: 11 82 浏览量
2008-05-27
10:28:52
上传
评论
收藏 1KB RAR 举报
shguxudong4
- 粉丝: 2
- 资源: 1
最新资源
- 2013-2022vc运行命令库
- probleme.exe
- 基于python完成对csv文件的读取并且通过flask框架显示
- 基于SpringBoot的“体质测试数据分析及可视化”的设计与实现.zip
- c语言-c语言编程基础之leetcode题解第21题合并两个有序链表.zip
- 快速开发API服务的框架
- c语言-c语言编程基础之leetcode题解第20题有效的括号.zip
- c语言-c语言编程基础之leetcode题解第19题删除链表的倒数第N个结点.zip
- c语言-c语言编程基础之leetcode题解第17题电话号码的字母组合.zip
- c语言-c语言编程基础之leetcode题解第16题最接近的三数之和.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈