/*
* BASIC INFORMATION:
* As this program is wriiten in Linux.So I write the information in English.
* By using Thread to achieve when you input a string then send
* Or receive a string then print
* September 9th ,2012
* By Jundai Xie,Anhui Normal University
* ------------------------------------------------------------------------------
*
* HOW TO USE:
*
*/
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Scanner;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
/**
* This is the class for Asynchronous Communication
*/
public class server extends java.lang.Thread
{
public void run()
{
// TODO Auto-generated method stub
//lisThread=new ListenThread(selector,sc);
//lisThread.start();
while(true)
{
try {
selector.select();///////////////////////////// Check each event is blocked or not
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
continue;
}
System.out.println("Here is start cycle");
ByteBuffer echoBuffer=ByteBuffer.allocate(10); //// Set a byte buffer to Storage datas
for (SelectionKey key : selector.selectedKeys())/// Traverse all events in the Cycle
{
selector.selectedKeys().remove(key);
//If this is an accepting event
if((key.readyOps()&SelectionKey.OP_ACCEPT)==SelectionKey.OP_ACCEPT)
{
System.out.println("监听事件:"+selector.keys().size());
System.out.println(key);
System.out.println("Server Listening...");
if(null!=key){
selector.selectedKeys().remove(key);
}
else {
System.out.println("Key is null in ListenThread");
}
ServerSocketChannel subssc=(ServerSocketChannel)key.channel();//Set a server socket channel
//Accept a socket
try {
sc=subssc.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
sc.configureBlocking(false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println("SC is registed!\n"+sc);
sc.register(selector, SelectionKey.OP_READ);
} catch (ClosedChannelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//将本此事件从迭带器中删除
System.out.println("有新连接:"+sc);
}
else if((key.readyOps()&SelectionKey.OP_READ)==SelectionKey.OP_READ)
{
System.out.println("接收事件:");
selector.selectedKeys().remove(key);//////////////////////////////// Delete this event
sc=(SocketChannel) key.channel();/////////////////////////////////// Create an socket object
ByteArrayOutputStream bos=new ByteArrayOutputStream();////////////// Create a stream object
echoBuffer.clear();
// Cycle will read client byte buffer,and the read function will return the length of data
// NIO will do all work automatically
int readInt=0;
try{
while((readInt=sc.read(echoBuffer)) > 0)
{
if(readInt<echoBuffer.capacity())
{
byte[] readByte=new byte[readInt];
for(int i=0;i<readInt;i++)
{
readByte[i]=echoBuffer.get(i);
}
bos.write(readByte);
}
else
{
bos.write(echoBuffer.array());
}
echoBuffer.clear();
}
System.out.println("Server接收数据: "+new String(bos.toByteArray()));
}
catch(IOException e)
{
e.printStackTrace();
key.cancel();
}
}
}
}
}
private int nPort;////////////////////////////////////// Default listening port
private SocketChannel sc;/////////////////////////////// Occasional socket
//private ReceiveThread thdReceive=null;/////////////////////// Receiving Thread
//private ListenThread lisThread=null;///////////////////////// Listening Thread
public int getNPort() {
return nPort;
}
public void setNPort(int port) {
nPort = port;
}
public SocketChannel getSc() {
return sc;
}
public void setSc(SocketChannel sc) {
this.sc = sc;
}
/**
* Event Selector
*/
private Selector selector;
/**
* Asynchronous Communication Object
*/
private ServerSocketChannel ssc;
/**
* Server Socket
*/
private ServerSocket ss;
/**
* Constructor without parameters
*/
public server()
{
initSocket(12345);
}
/**
* Constructor with port parameter
* @param pt : The port of server socket listening
*/
public server(int pt)
{
initSocket(pt);
}
/**
* Initialization function for Asynchronous Communication
* @param pt : Listening port
* @return Is There any exception in this function
*/
private boolean initSocket(int pt)
{
try
{
selector = Selector.open(); //////////////////////////// Set an event selector to record socket events
ssc = ServerSocketChannel.open();///////////////////////// An Asynchronous Communication Object
ssc.configureBlocking(false);///////////////////////////// Set Asynchronous Communication mod
ss = ssc.socket();//////////////////////////////////////// Set server socket
InetSocketAddress address = new InetSocketAddress(pt);//// Address Object
ss.bind(address);///////////////////////////////////////// Bing the server and address
ssc.register(selector, SelectionKey.OP_ACCEPT);/////////// Register Asynchronous Communication socket Object to seelector
System.out.println("Server:端口注册完毕!");
return true;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
/**
* Send a string message to client
* @param str : The string that will be sended
*/
public boolean SendInfo(String str)
{
// this.sc=lisThread.getSc();
System.out.println(sc);
if(null==sc) return false;
ByteBuffer bf=ByteBuffer.allocate(500);
bf.put(str.getBytes());
bf.flip();
try {
sc.write(bf);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
/**
* Overloaded Function SendInfo
* @param echoBuffer : Byte infos
*/
public boolean SendInfo(ByteBuffer echoBuffer)
{
//this.sc=lisThread.getSc();
if(null==sc) return false;
echoBuffer.flip();
try
{
sc.write(echoBuffer);
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
JavaNioTamplateServer.rar (6个子文件)
JavaNioTamplateServer
bin
server.class 5KB
Main.class 1KB
src
server.java 8KB
Main.java 549B
.project 397B
.classpath 232B
共 6 条
- 1
资源评论
- tngworld2013-03-12有借鉴价值,值得下载。
- lxf6345481322013-12-04很详细 值得学习
- huntsman_tt2014-04-02很详细,非常好
- jamessg2014-08-27有借鉴价值,值得下载
- 3835749112013-03-21有借鉴价值,值得下载。
feiya
- 粉丝: 3
- 资源: 20
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功