热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

socket与mina交互数据

之前网上查了些资料,有些blog说mina做服务端,socket做客户端,没法用DemuxingProtocolCodecFactory,只能用TextLineCodecFactory协议解析,但要是

之前网上查了些资料,有些blog说mina做服务端,socket做客户端,没法用DemuxingProtocolCodecFactory,只能用TextLineCodecFactory协议解析,但要是传文件,这个东东根本就没用,事实上,服务器很大可能是要传文件的,mina做服务端,客户端可能是不同的。比如用mina的客户端写,用nio自己写,用socket自己写,用C语言自己写。

本次测试例子:使用socket传送较长字符串,如果传送文件,也是一样的过程,先将字符串或者文件转换成byte数组

其实如果理解mina的协议解析的话就会非常简单处理这些解码:

大体思想:协议一般有头信息 告诉程序需要读取多少字节,程序就可以不断读取了,知道在哪个字节时候就不用再往后读了。

IoBuffer读取的时候就像一个管道,读取了这部分数据,这部分数据就没有,其实IO流就是这样

Socket客户端:

package com.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;


public class client {



public static void main(String[] args) throws Exception{
Socket socket = new Socket("127.0.0.1",9123);
OutputStream os = socket.getOutputStream();
String str = "";
for(int i=0;i<100;i++){
str = str + "我们都是中国人啊!";
}
byte[] bytes = str.getBytes("utf-8");
System.out.println("数据byte长度:"+bytes.length);
os.write(i2b(bytes.length));
os.write(bytes);
os.flush();

InputStream is = null;

is = socket.getInputStream();
byte[] intByte = new byte[4];
is.read(intByte);
int msgLength = b2i(intByte);
System.out.println("int:"+msgLength);
int readPosition = 0;
byte[] byteArray = new byte[msgLength];
while(readPosition int value = is.read(byteArray, readPosition, msgLength-readPosition);
if(value == -1){
break;
}
readPosition += value;

}
System.out.println(new String(byteArray,"utf-8"));
System.out.println("byteArray Length:"+byteArray.length+" string Length:"+new String(byteArray,"utf-8").length());
if(os != null){
os.close();
}
if(is != null){
is.close();
}
}

// 网上抄来的,将 int 转成字节
public static byte[] i2b(int i) {
return new byte[] { (byte) ((i >> 24) & 0xFF),
(byte) ((i >> 16) & 0xFF), (byte) ((i >> 8) & 0xFF),
(byte) (i & 0xFF) };
}

public static int b2i(byte[] b) {
int value = 0;
for (int i = 0; i <4; i++) {
int shift = (4 - 1 - i) * 8;
value += (b[i] & 0x000000FF) <}
return value;
}

}
socket先发送测试数据,然后接收服务端返回的数据

package com.test;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.demux.MessageDecoder;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;



public class BaseMessageDecoder implements MessageDecoder {
AttributeKey COnTEXT= new AttributeKey(getClass(),"context");
/**
* 是否适合解码
* */
public MessageDecoderResult decodable(IoSession session, IoBuffer in) {

// TODO Auto-generated method stub

return MessageDecoderResult.OK;
}

/**
* 数据解码
* */
public MessageDecoderResult decode(IoSession session, IoBuffer in,
ProtocolDecoderOutput outPut) throws Exception {
// TODO Auto-generated method stub
Context cOntext= (Context) session.getAttribute(CONTEXT);
// TODO Auto-generated method stub
IoBuffer buffer = in;
if(cOntext== null || !context.init){
IoBuffer b = buffer.get(new byte[4]);
byte[] intByte = b.array();
int num = b2i(intByte);
System.out.println("长度:"+num);
cOntext= new Context();
context.number = num;
context.position = 0;
context.byteArray = new byte[num];
context.init = true;
while(buffer.hasRemaining()){
byte c = buffer.get();
context.byteArray[context.position] = c;
context.position++;
}
}else{
while(buffer.hasRemaining()){
byte c = buffer.get();
context.byteArray[context.position] = c;
if( context.position == context.number-1){
System.out.println(new String(context.byteArray,"utf-8"));
IoBuffer buff = IoBuffer.allocate(1024).setAutoExpand(true);
buff.put(i2b(context.number));
buff.put(context.byteArray);
buff.flip();
outPut.write(buff);
return MessageDecoderResult.OK;
}
context.position++;
}
}
session.setAttribute(CONTEXT,context);
return MessageDecoderResult.NEED_DATA;
}

/**
* 解码完成
* */
public void finishDecode(IoSession session, ProtocolDecoderOutput outPut)
throws Exception {
// TODO Auto-generated method stub
}
public static int b2i(byte[] b) {
int value = 0;
for (int i = 0; i <4; i++) {
int shift = (4 - 1 - i) * 8;
value += (b[i] & 0x000000FF) <}
return value;
}
public static byte[] i2b(int i) {
return new byte[] { (byte) ((i >> 24) & 0xFF),
(byte) ((i >> 16) & 0xFF), (byte) ((i >> 8) & 0xFF),
(byte) (i & 0xFF) };
}
class Context {
public Integer number;
public byte[] byteArray;
public Integer position;
public boolean init;
}
}
因传送字符串较长,执行多次调用decode方法,需要中间变量记住之前的部分字段值。

IoBuffer buff = IoBuffer.allocate(1024).setAutoExpand(true);
buff.put(i2b(context.number));
buff.put(context.byteArray);
buff.flip();
outPut.write(buff);

这段代码本应该写在BaseMessageEncoder的encode方法中,但出于我并没有在服务端需要这些字符串值,所以直接将数据方法IoBuffer,服务端直接写回客户端

测试数据OK。

源代码



推荐阅读
  • iOS超签签名服务器搭建及其优劣势
    本文介绍了搭建iOS超签签名服务器的原因和优势,包括不掉签、用户可以直接安装不需要信任、体验好等。同时也提到了超签的劣势,即一个证书只能安装100个,成本较高。文章还详细介绍了超签的实现原理,包括用户请求服务器安装mobileconfig文件、服务器调用苹果接口添加udid等步骤。最后,还提到了生成mobileconfig文件和导出AppleWorldwideDeveloperRelationsCertificationAuthority证书的方法。 ... [详细]
  • 基于Socket的多个客户端之间的聊天功能实现方法
    本文介绍了基于Socket的多个客户端之间实现聊天功能的方法,包括服务器端的实现和客户端的实现。服务器端通过每个用户的输出流向特定用户发送消息,而客户端通过输入流接收消息。同时,还介绍了相关的实体类和Socket的基本概念。 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 本文介绍了UVALive6575题目Odd and Even Zeroes的解法,使用了数位dp和找规律的方法。阶乘的定义和性质被介绍,并给出了一些例子。其中,部分阶乘的尾零个数为奇数,部分为偶数。 ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • 本文介绍了南邮ctf-web的writeup,包括签到题和md5 collision。在CTF比赛和渗透测试中,可以通过查看源代码、代码注释、页面隐藏元素、超链接和HTTP响应头部来寻找flag或提示信息。利用PHP弱类型,可以发现md5('QNKCDZO')='0e830400451993494058024219903391'和md5('240610708')='0e462097431906509019562988736854'。 ... [详细]
  • 开发笔记:Java是如何读取和写入浏览器Cookies的
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了Java是如何读取和写入浏览器Cookies的相关的知识,希望对你有一定的参考价值。首先我 ... [详细]
  • Imtryingtofigureoutawaytogeneratetorrentfilesfromabucket,usingtheAWSSDKforGo.我正 ... [详细]
  • mac php错误日志配置方法及错误级别修改
    本文介绍了在mac环境下配置php错误日志的方法,包括修改php.ini文件和httpd.conf文件的操作步骤。同时还介绍了如何修改错误级别,以及相应的错误级别参考链接。 ... [详细]
  • 纠正网上的错误:自定义一个类叫java.lang.System/String的方法
    本文纠正了网上关于自定义一个类叫java.lang.System/String的错误答案,并详细解释了为什么这种方法是错误的。作者指出,虽然双亲委托机制确实可以阻止自定义的System类被加载,但通过自定义一个特殊的类加载器,可以绕过双亲委托机制,达到自定义System类的目的。作者呼吁读者对网上的内容持怀疑态度,并带着问题来阅读文章。 ... [详细]
  • 本文介绍了Android中的assets目录和raw目录的共同点和区别,包括获取资源的方法、目录结构的限制以及列出资源的能力。同时,还解释了raw目录中资源文件生成的ID,并说明了这些目录的使用方法。 ... [详细]
author-avatar
曾玉珊志君
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有