smartfoxserver扩展里面过滤聊天的不合法字符

http://blog.csdn.net/yc7369/article/details/35567105

近期做手游客户要求加上一个聊天功能。事实上嘛,个人认为这个聊天功能比較鸡肋,这部分差点儿已经有tx被垄断,我们又何苦倘这趟浑水呢。手游聊天的游戏事实上并不多。

主要原因非常easy:server的负载会增大不少,维护更加麻烦,烧钱,而用这个功能的人也不会太多。也会出现server调控下的各种穿帮。

既然要趟这浑水,那也就没办法。聊天系统推断聊天内容是否包括有不合法字符还是须要的。

使用的是smartfoxserver服务器扩展。由于SFS默认它是UTF-8编码的,除了英文以外发送过来的字符都是会乱码的,所以我想了一天想到了以下的方法供大家參考。假设有不正确的地方请留言提出!

try {

     String[] keyword = { "操", "fuck", "叼", "cao" };
String content = json.getString("content").trim();

Pattern p = Pattern.compile("\\s*|\t|\r|\n"); //正則表達式
Matcher m = p.matcher(content);
String after = m.replaceAll(""); //把所有上述表达式的东西所有换成空字符串

after = MsgTool.gbkToutf8(after); //把所用的字符都所有转化为UTF-8编码,这样就不会出现编码问题而不能比較

boolean flag = false; // 推断是否包括屏蔽字符

for (int i = 0; i < keyword.length; i++) {

String kw = MsgTool.gbkToutf8(keyword[i]);

if (after.indexOf(kw) != -1) { //假设包括有的话就返回
flag = true;
break;
}
}

MsgJSONObject msj = MsgJSONObject.instance();

if (flag) {
log.info("实用户聊天时发送不合法字符,用户是:" + user.getName()); //发送给client说用户的聊天内容有不合法字符
msj.put("cmd", "chatUnlawful");
sendMessage(user, msj);

} else { //假设没有就正常发送

log.info("实用户聊天,用户是:" + user.getName());
log.info("聊天内容是:" + content);
msj.put("cmd", "chat");
msj.put("msg", content);
sendMessage(getRoom(user), msj);
}

} catch (Exception e) {
e.printStackTrace();
log.error("读取聊天内容错误");
}

/**编码转换。将中文变为UTF-8
* @param chenese 要中文字符
* @return
*/
public static String gbkToutf8(String chinese){
char c[] = chinese.toCharArray();
byte [] fullByte =new byte[3*c.length];
for(int i=0; i<c.length; i++){
int m = (int)c[i];
String word = Integer.toBinaryString(m);

StringBuffer sb = new StringBuffer();
int len = 16 - word.length();
//补零
for(int j=0; j<len; j++){
sb.append("0");
}
sb.append(word);
sb.insert(0, "1110");
sb.insert(8, "10");
sb.insert(16, "10");

String s1 = sb.substring(0, 8);
String s2 = sb.substring(8, 16);
String s3 = sb.substring(16);

byte b0 = Integer.valueOf(s1, 2).byteValue();
byte b1 = Integer.valueOf(s2, 2).byteValue();
byte b2 = Integer.valueOf(s3, 2).byteValue();
byte[] bf = new byte[3];
bf[0] = b0;
fullByte[i*3] = bf[0];
bf[1] = b1;
fullByte[i*3+1] = bf[1];
bf[2] = b2;
fullByte[i*3+2] = bf[2];

}

try {
String fullStr = new String(fullByte, "UTF-8");
return fullStr;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error("转换字符编码错误");
return "";
}

}

http://blog.csdn.net/yc7369/article/details/35567105


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值