服务器代码:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
public class server
{
//
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
public class server
{
//
定义一个临时的socket
SocketChannel sc;
public void start()
{
try
{
//定义一个事件选择器对象记录套接字通道的事件
Selector selector = Selector.open();
//定义一个异步服务器socket对象
ServerSocketChannel ssc=ServerSocketChannel.open();
//将此socket对象设置为异步
ssc.configureBlocking(false);
//定义服务器socket对象-用来指定异步socket的监听端口等信息
ServerSocket ss=ssc.socket();
//定义存放监听端口的对象
InetSocketAddress address = new InetSocketAddress(55555);
//将服务器与这个端口绑定
ss.bind(address);
//将异步的服务器socket对象的接受客户端连接事件注册到selector对象内
ssc.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("端口注册完毕!");
//通过此循环来遍例事件
while(true)
{
//查询事件如果一个事件都没有就阻塞
selector.select();
//定义一个byte缓冲区来存储收发的数据
ByteBuffer echoBuffer=ByteBuffer.allocate(10);
SocketChannel sc;
public void start()
{
try
{
//定义一个事件选择器对象记录套接字通道的事件
Selector selector = Selector.open();
//定义一个异步服务器socket对象
ServerSocketChannel ssc=ServerSocketChannel.open();
//将此socket对象设置为异步
ssc.configureBlocking(false);
//定义服务器socket对象-用来指定异步socket的监听端口等信息
ServerSocket ss=ssc.socket();
//定义存放监听端口的对象
InetSocketAddress address = new InetSocketAddress(55555);
//将服务器与这个端口绑定
ss.bind(address);
//将异步的服务器socket对象的接受客户端连接事件注册到selector对象内
ssc.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("端口注册完毕!");
//通过此循环来遍例事件
while(true)
{
//查询事件如果一个事件都没有就阻塞
selector.select();
//定义一个byte缓冲区来存储收发的数据
ByteBuffer echoBuffer=ByteBuffer.allocate(10);