xSocket是一个轻量级的基于nio的服务器框架用于开发高性能、可扩展、多线程的服务器。该框架封装了线程处理、异步读/写等方面。
http://www.xsocket.org/
API:
http://xsocket.sourceforge.net/core/apidocs/2_1/index.html
http://xsocket.sourceforge.net/core/apidocs/2_1_1/index.html
下载:http://download.csdn.net/source/593929
用xSocket做了个服务端,客户端用开始的flex做的那个聊天室
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
//
Main.java
package chat;
import org.xsocket.connection. * ;
public class Main {
/** Choose your favorite port number. */
private static final int PORT = 8014 ;
public static void main(String[] args) throws Exception {
// creates the server by passing over the port number & handler
IServer srv = new Server(PORT, new EchoHandler());
// srv.setFlushmode(FlushMode.ASYNC);
// run it within the current thread.
try {
// srv.run(); // the call will not return
// ... or start it by using a dedicated thread
srv.start(); // returns after the server has been started
System.out.println( " 服务器 " + srv.getLocalAddress() + " : " + PORT);
} catch (Exception e){
System.out.println(e);
}
// System.out.println("日志: " + srv.getStartUpLogMessage());
}
}
// EchoHandler.java
package chat;
import org.xsocket.connection. * ;
import org.xsocket. * ;
import java.nio. * ;
import java.io. * ;
import java.util. * ;
class EchoHandler implements IDataHandler,IConnectHandler,IDisconnectHandler {
public static BManager bMan = new BManager();
public static Map < INonBlockingConnection,String > clientList = new HashMap < INonBlockingConnection,String > ();
public boolean onConnect(INonBlockingConnection nbc) throws IOException {
// ... e.g. open resources
System.out.println( " onConnect " + nbc.getRemoteAddress() + " : " + nbc.getRemotePort());
return true ;
}
public boolean onDisconnect(INonBlockingConnection nbc) throws IOException {
// ... e.g. closing open resources
System.out.println( " onDisconnect " + nbc.getRemoteAddress() + " : " + nbc.getRemotePort());
bMan.remove(nbc);
if (clientList.containsKey(nbc))
{
bMan.sendToAll( " 22 " + clientList.get(nbc) + " 离开了... " );
clientList.remove(nbc);
funList(clientList);
}
bMan.sendClientInfo();
return true ;
}
public boolean onData(INonBlockingConnection connection)
throws IOException,
BufferUnderflowException,
MaxReadSizeExceededException {
// byte[] bytes = connection.readBytesByDelimiter("\n");
// String head = new String(by);
String cmd = connection.readStringByDelimiter( " \n " , " utf8 " );
System.out.println( " Get Data " + cmd);
if (cmd.equals( " <policy-file-request/>\0 " ))
{
String xml = " <cross-domain-policy> " ;
xml = xml + " <site-control permitted-cross-domain-policies=\"all\"/> " ;
xml = xml + " <allow-access-from domain=\"*\" to-ports=\"8014\" /> " ;
xml = xml + " </cross-domain-policy> " ;
connection.write(xml + " \0 " );
}
else {
String str = cmd.substring( 0 , 2 ); // 截取第一个字符
int a = Integer.parseInt(str);
String[] arrMsg = cmd.split( " -- " );
switch (a)
{
case 11 :
String strName = cmd.substring( 2 );
cmd = " 22 " + strName + " login " ; // ""登陆了";
System.out.println(cmd);
// connection.write(cmd);
bMan.add(connection);
clientList.put(connection,strName); // 加入到HashMap中
bMan.sendToAll(cmd); // 广播谁登陆了
funList(clientList);
bMan.sendClientInfo();
break ;
case 22 :
// cmd=arrMsg[0]+arrMsg[1]+"说:"+arrMsg[2];
cmd = arrMsg[ 0 ] + arrMsg[ 1 ] + " say: " + arrMsg[ 2 ];
// connection.write(cmd,"utf8");
bMan.sendToAll(cmd);
System.out.println( " 公聊 " + cmd);
break ;
case 33 :
if (arrMsg[ 1 ].equals( " 所有人 " ))
{
cmd = arrMsg[ 2 ] + " 说: " + arrMsg[ 3 ];
bMan.sendToAll( " 22 " + cmd);
} else
{
INonBlockingConnection socketOne;
System.out.println( " 私聊 " );
Set set = clientList.keySet(); // 使用keySet方法获取所有key值
Iterator it = set.iterator();
while (it.hasNext()) {
Object ok = it.next();
Object ov = clientList.get(ok);
if (ov.equals(arrMsg[ 1 ])) // 发给对方
{
socketOne = (INonBlockingConnection)ok;
bMan.sendToONE(socketOne, " 22(悄悄话) " + arrMsg[ 2 ] + " 对你说: " + arrMsg[ 3 ]);
} else if (ov.equals(arrMsg[ 2 ])) // 发给自己
{
socketOne = (INonBlockingConnection)ok;
bMan.sendToONE(socketOne, " 22(悄悄话)你对 " + arrMsg[ 1 ] + " 说: " + arrMsg[ 3 ]);
}
}
}
break ;
}
}
return true ;
}
void funList(Map clientList) // 广播在线列表
{
String strList = "" ; // 在线列表
Set set = clientList.keySet(); // 使用keySet方法获取所有key值
// System.out.println(set);
Iterator it = set.iterator();
// System.out.println(it);
while (it.hasNext()) { // 把用户名称发给在线所有客户端
strList += " -- " ;
strList += clientList.get(it.next());
}
bMan.sendToAll( " 11 " + strList);
}
}
// 管理客户端类
// BManager.java
package chat;
import java.io. * ;
import java.util. * ;
import org.xsocket.connection. * ;
class BManager extends Vector
{
BManager (){}
void add(INonBlockingConnection sock)
{
super .add(sock);
}
void remove(INonBlockingConnection sock)
{
super .remove(sock);
}
synchronized void sendToAll(String msg)
{
// PrintWriter writer=null;
INonBlockingConnection sock;
System.out.println( " 发送 " + msg + " / " + size());
for ( int i = 0 ;i < size();i ++ )
{
sock = (INonBlockingConnection)elementAt(i);
try
{
sock.write(msg);
System.out.println( " 发送 " + sock.getRemoteAddress() + " : " + sock.getRemotePort() + " | " + msg);
// writer=new PrintWriter(sock.getOutputStream(),true);
} catch (Exception ie){}
// if(writer!=null)writer.println(msg);
}
}
synchronized void sendToONE(INonBlockingConnection socket,String msg)
{
// PrintWriter writer=null;
INonBlockingConnection sock;
for ( int i = 0 ;i < size();i ++ )
{
sock = (INonBlockingConnection)elementAt(i);
if (socket == sock)
{
try
{
sock.write(msg);
// writer=new PrintWriter(sock.getOutputStream(),true);
} catch (Exception ie){}
// if(writer!=null)writer.println(msg);
}
}
}
synchronized void sendClientInfo()
{
String info = " 44当前聊天人数: " + size();
// System.out.println(info);
sendToAll(info);
}
}
package chat;
import org.xsocket.connection. * ;
public class Main {
/** Choose your favorite port number. */
private static final int PORT = 8014 ;
public static void main(String[] args) throws Exception {
// creates the server by passing over the port number & handler
IServer srv = new Server(PORT, new EchoHandler());
// srv.setFlushmode(FlushMode.ASYNC);
// run it within the current thread.
try {
// srv.run(); // the call will not return
// ... or start it by using a dedicated thread
srv.start(); // returns after the server has been started
System.out.println( " 服务器 " + srv.getLocalAddress() + " : " + PORT);
} catch (Exception e){
System.out.println(e);
}
// System.out.println("日志: " + srv.getStartUpLogMessage());
}
}
// EchoHandler.java
package chat;
import org.xsocket.connection. * ;
import org.xsocket. * ;
import java.nio. * ;
import java.io. * ;
import java.util. * ;
class EchoHandler implements IDataHandler,IConnectHandler,IDisconnectHandler {
public static BManager bMan = new BManager();
public static Map < INonBlockingConnection,String > clientList = new HashMap < INonBlockingConnection,String > ();
public boolean onConnect(INonBlockingConnection nbc) throws IOException {
// ... e.g. open resources
System.out.println( " onConnect " + nbc.getRemoteAddress() + " : " + nbc.getRemotePort());
return true ;
}
public boolean onDisconnect(INonBlockingConnection nbc) throws IOException {
// ... e.g. closing open resources
System.out.println( " onDisconnect " + nbc.getRemoteAddress() + " : " + nbc.getRemotePort());
bMan.remove(nbc);
if (clientList.containsKey(nbc))
{
bMan.sendToAll( " 22 " + clientList.get(nbc) + " 离开了... " );
clientList.remove(nbc);
funList(clientList);
}
bMan.sendClientInfo();
return true ;
}
public boolean onData(INonBlockingConnection connection)
throws IOException,
BufferUnderflowException,
MaxReadSizeExceededException {
// byte[] bytes = connection.readBytesByDelimiter("\n");
// String head = new String(by);
String cmd = connection.readStringByDelimiter( " \n " , " utf8 " );
System.out.println( " Get Data " + cmd);
if (cmd.equals( " <policy-file-request/>\0 " ))
{
String xml = " <cross-domain-policy> " ;
xml = xml + " <site-control permitted-cross-domain-policies=\"all\"/> " ;
xml = xml + " <allow-access-from domain=\"*\" to-ports=\"8014\" /> " ;
xml = xml + " </cross-domain-policy> " ;
connection.write(xml + " \0 " );
}
else {
String str = cmd.substring( 0 , 2 ); // 截取第一个字符
int a = Integer.parseInt(str);
String[] arrMsg = cmd.split( " -- " );
switch (a)
{
case 11 :
String strName = cmd.substring( 2 );
cmd = " 22 " + strName + " login " ; // ""登陆了";
System.out.println(cmd);
// connection.write(cmd);
bMan.add(connection);
clientList.put(connection,strName); // 加入到HashMap中
bMan.sendToAll(cmd); // 广播谁登陆了
funList(clientList);
bMan.sendClientInfo();
break ;
case 22 :
// cmd=arrMsg[0]+arrMsg[1]+"说:"+arrMsg[2];
cmd = arrMsg[ 0 ] + arrMsg[ 1 ] + " say: " + arrMsg[ 2 ];
// connection.write(cmd,"utf8");
bMan.sendToAll(cmd);
System.out.println( " 公聊 " + cmd);
break ;
case 33 :
if (arrMsg[ 1 ].equals( " 所有人 " ))
{
cmd = arrMsg[ 2 ] + " 说: " + arrMsg[ 3 ];
bMan.sendToAll( " 22 " + cmd);
} else
{
INonBlockingConnection socketOne;
System.out.println( " 私聊 " );
Set set = clientList.keySet(); // 使用keySet方法获取所有key值
Iterator it = set.iterator();
while (it.hasNext()) {
Object ok = it.next();
Object ov = clientList.get(ok);
if (ov.equals(arrMsg[ 1 ])) // 发给对方
{
socketOne = (INonBlockingConnection)ok;
bMan.sendToONE(socketOne, " 22(悄悄话) " + arrMsg[ 2 ] + " 对你说: " + arrMsg[ 3 ]);
} else if (ov.equals(arrMsg[ 2 ])) // 发给自己
{
socketOne = (INonBlockingConnection)ok;
bMan.sendToONE(socketOne, " 22(悄悄话)你对 " + arrMsg[ 1 ] + " 说: " + arrMsg[ 3 ]);
}
}
}
break ;
}
}
return true ;
}
void funList(Map clientList) // 广播在线列表
{
String strList = "" ; // 在线列表
Set set = clientList.keySet(); // 使用keySet方法获取所有key值
// System.out.println(set);
Iterator it = set.iterator();
// System.out.println(it);
while (it.hasNext()) { // 把用户名称发给在线所有客户端
strList += " -- " ;
strList += clientList.get(it.next());
}
bMan.sendToAll( " 11 " + strList);
}
}
// 管理客户端类
// BManager.java
package chat;
import java.io. * ;
import java.util. * ;
import org.xsocket.connection. * ;
class BManager extends Vector
{
BManager (){}
void add(INonBlockingConnection sock)
{
super .add(sock);
}
void remove(INonBlockingConnection sock)
{
super .remove(sock);
}
synchronized void sendToAll(String msg)
{
// PrintWriter writer=null;
INonBlockingConnection sock;
System.out.println( " 发送 " + msg + " / " + size());
for ( int i = 0 ;i < size();i ++ )
{
sock = (INonBlockingConnection)elementAt(i);
try
{
sock.write(msg);
System.out.println( " 发送 " + sock.getRemoteAddress() + " : " + sock.getRemotePort() + " | " + msg);
// writer=new PrintWriter(sock.getOutputStream(),true);
} catch (Exception ie){}
// if(writer!=null)writer.println(msg);
}
}
synchronized void sendToONE(INonBlockingConnection socket,String msg)
{
// PrintWriter writer=null;
INonBlockingConnection sock;
for ( int i = 0 ;i < size();i ++ )
{
sock = (INonBlockingConnection)elementAt(i);
if (socket == sock)
{
try
{
sock.write(msg);
// writer=new PrintWriter(sock.getOutputStream(),true);
} catch (Exception ie){}
// if(writer!=null)writer.println(msg);
}
}
}
synchronized void sendClientInfo()
{
String info = " 44当前聊天人数: " + size();
// System.out.println(info);
sendToAll(info);
}
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/wind520/archive/2008/09/02/2865039.aspx