Boostasio异步TCP通讯与tcp粘包解包解决方案.docx
《Boostasio异步TCP通讯与tcp粘包解包解决方案.docx》由会员分享,可在线阅读,更多相关《Boostasio异步TCP通讯与tcp粘包解包解决方案.docx(22页珍藏版)》请在冰豆网上搜索。
Boostasio异步TCP通讯与tcp粘包解包解决方案
Boostasio异步TCP通讯及tcp粘包解包解决方案
Sphinx调用命令列表[Shell/批处理],Spring连接MySQLOracle和SQLServer的数
sql防注入的登录注册[SQL],Struts2剔除Ongl表达式危险的数据类型。
SVG绘制圆弧
svn小冲突解决笔记
tableview全面自定制
intmain()
{
namespaceip=boost:
:
asio:
:
ip;
boost:
:
asio:
:
io_serviceio_service;
//Serverbindstoanyaddressandanyport.
ip:
:
udp:
:
socketsocket(io_service,
ip:
:
udp:
:
endpoint(ip:
:
udp:
:
v4(),0));
socket.set_option(boost:
:
asio:
:
socket_base:
:
broadcast(true));
//Broadcastwillgotoport8888.
ip:
:
udp:
:
endpointbroadcast_endpoint(ip:
:
address_v4:
:
broadcast(),8888);
//Broadcastdata.
〃boost:
:
arraybuffer;
char*buf="测试代码";
socket.send_to(boost:
:
asio:
:
buffer(buf,strlen(buf)+1),broadcast_endpoint);
}
//jQuery地区三级联动选择输入
〃js动画完美框架[文件]skiplist.cpp~5KB
/*skiplist*/
#include
#include
/*implementationdependentdeclarations*/typedefenum{
STATUS_OK,
STATUS_MEM_EXHAUSTED,
STATUS_DUPLICATE_KEY,
STATUS_KEY_NOT_FOUND
}statusEnum;
//js实现鼠标hover时tab自动切换typedefintkeyType;/*typeofkey*/
/*userdatastoredintree*/
typedefstruct{
intstuff;/*optionalrelateddata*/
}recType;
#definecompLT(a,b)(a
#definecompEQ(a,b)(a==b)
/*levelsrangefrom(0..MAXLEVEL)*/#defineMAXLEVEL15
typedefstructnodeTag{
keyTypekey;/*keyusedforsearching*/
recTyperec;/*userdata*/
structnodeTag*forward[1];/*skiplistforwardpointer*/}nodeType;
[代码][GoogleGo]代码
packagemain
import(
"io/ioutil"
"net/http"
"net/"
"fmt"
"encoding/json"
)
//
//黄金数据调用示例代码-聚合数据
//在线接口文档:
/docs/29
//
constAPPKEY=
“*******************“
//
您申请的APPKEY
funcmain(){
//1.黄金交易所
Request1()
〃2.期货交易所
Request2()
〃3.银行账户黄金
Request3()
}
//1.黄金交易所
funcRequest1(){
//请求地址
juhe:
="web:
8080/finance/gold/shgold"
//初始化参数
param:
=.Values{}
//配置请求参数,方法部已处理encode问题,中文参数可以直接传参
param.Set("key",APPKEY)//APPKey
param.Set("v","")//JSON格式版本(0或1)默认为0
data,err:
=Get(juhe,param)
iferr!
=nil{
fmt.Errorf(”请求失败,错误信息:
\r\n%v",err)
}else{
varnetReturnmap[string]interface{}
json.Unmarshal(data,&netReturn)
ifnetReturn["error_code"].(float64)==0{
fmt.Printf("接口返回result字段是:
\r\n%v",netReturn["result"])
}
}
}
〃2.期货交易所
funcRequest2(){
//请求地址
juhe:
="web:
8080/finance/gold/shfuture"
//初始化参数
param:
=.Values{}
//配置请求参数,方法部已处理encode问题,中文参数可以直接传参
param.Set("key",APPKEY)//APPKey
param.Set("v","")//JSON格式版本(0或1)默认为0
data,err:
=Get(juhe,param)
iferr!
=nil{
fmt.Errorf(”请求失败,错误信息:
\r\n%v",err)
}else{
varnetReturnmap[string]interface{}
json.Unmarshal(data,&netReturn)
ifnetReturn["error_code"].(float64)==0{
fmt.Printf("接口返回result字段是:
\r\n%v",netReturn["result"])
}
}
}
〃3.银行账户黄金
funcRequest3(){
//请求地址
juhe:
="web:
8080/finance/gold/bankgold"
//初始化参数
param:
=.Values{}
//配置请求参数,方法部已处理encode问题,中文参数可以直接传参
param.Set("key",APPKEY)//APPKey
data,err:
=Get(juhe,param)
iferr!
=nil{
fmt.Errorf(”请求失败,错误信息:
\r\n%v",err)
}else{
varnetReturnmap[string]interface{}
json.Unmarshal(data,&netReturn)
ifnetReturn["error_code"].(float64)==0{
fmt.Printf("接口返回result字段是:
\r\n%v",netReturn["result"])
}
}
}
//get网络请求
funcGet(apistring,params.Values)(rs[]byte,errerror){
var*.
err=.Parse(api)
iferr!
=nil{
fmt.Printf("解析错误:
\r\n%v",err)
returnnil,err
}
//如果参数中有中文参数,这个方法会进行Encode
.RawQuery=params.Encode()
resp,err:
=http.Get(.String())
iferr!
=nil{
fmt.Println("err:
",err)
returnnil,err
}
deferresp.Body.Close()
returnioutil.ReadAII(resp.Body)
}
//post网络请求,params是.Values类型
funcPost(apistring,params.Values)(rs[]byte,errerror){resp,err:
=http.PostForm(api,params)
iferr!
=nil{
returnnil,err
}
deferresp.Body.Close()
returnioutil.ReadAII(resp.Body)
}
代码描述:
基于GO的黄金数据接口调用代码实例关联数据:
黄金数据
[代码][C#]代码
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Net;
usingSystem.Diagnosties;
usingSystem.Web;
//
//黄金数据调用示例代码-聚合数据
//在线接口文档:
/docs/29
//代码中JsonObject类下载地址:
/download/gcm65/7458439
//
namespaceConsoleAPI
{
classProgram
{
staticvoidMain(string[]args)
{
appkey
stringappkey="*******************";//配置您申请的
//1.黄金交易所
string1="web:
8080/finance/gold/shgold";
varparametersl=newDictionary();
stringresultl=sendPost(1,parametersl,"get");
JsonObjectnewObjl=newJsonObject(resultl);
StringerrorCode1=newObj1["error_code"].Value;
if(errorCode1=="0")
{
Debug.WriteLine(”成功");
Debug.WriteLine(newObj1);
}
else
//Debug.WriteLine(”失败");
Debug.WriteLine(newObj1["error_code"].Value+":
"+newObj1["reason"].Value);
}
〃2.期货交易所
string2="web:
8080/finance/gold/shfuture";
varparameters2=newDictionary();
stringresult2=sendPost(2,parameters2,"get");
JsonObjectnewObj2=newJsonObject(result2);
StringerrorCode2=newObj2["error_code"].Value;
if(errorCode2=="0")
{
Debug.WriteLine(”成功");
Debug.WriteLine(newObj2);
}
else
{
//Debug.WriteLine("失败");
Debug.WriteLine(newObj2["error_code"].Value+":
"+newObj2["reason"].Value);
}
//3.银行账户黄金
string3="web:
8080/finance/gold/bankgold";
你申请的key
parameters3.Add("key",appkey);//
stringresult3=sendPost(3,parameters3,"get");
JsonObjectnewObj3=newJsonObject(result3);
StringerrorCode3=newObj3["error_code"].Value;
if(errorCode3=="0")
{
Debug.WriteLine(”成功");
Debug.WriteLine(newObj3);
}
else
{
//Debug.WriteLine("失败");
Debug.WriteLine(newObj3["error_code"].Value+":
"+newObj3["reason"].Value);
}
}
///
///Http(GET/POST)
///
///vparamname="parameters">请求参数
///vparamname="method">请求方法
///vreturns>响应容v/returns>
staticstringsendPost(string,IDictionaryvstring,string>parameters,stringmethod)
{
if(method.ToLower()=="post")
{
HttpWebRequestreq=null;
HttpWebResponsersp=nuII;
System.IO.StreamreqStream=nuII;
try
{
req=(HttpWebRequest)WebRequest.Create();
req.Method=method;
req.KeepAlive=false;
req.ProtocolVersion=HttpVersion.Version10;
req.Timeout=5000;
req.ContentType=
"application/x--form-encoded;charset=utf-8";
byte[]postData=
Encoding.UTF8.GetBytes(BuildQuery(parameters,"utf8"));
reqStream=req.GetRequestStream();
reqStream.Write(postData,0,postData.Length);
rsp=(HttpWebResponse)req.GetResponse();
Encodingencoding=Encoding.GetEncoding(rsp.CharacterSet);
returnGetResponseAsString(rsp,encoding);
}
catch(Exceptionex)
{
returnex.Message;
}
finally
{
if(reqStream!
=null)reqStream.Close();
if(rsp!
=null)rsp.Close();
}
}
else
{
//创建请求
HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(+"?
"
+BuildQuery(parameters,"utf8"));
//GET请求
request.Method="GET";
request.ReadWriteTimeout=5000;
request.ContentType="text/html;charset=UTF-8";
HttpWebResponseresponse=
(HttpWebResponse)request.GetResponse();
StreammyResponseStream=response.GetResponseStream();
StreamReader
myStreamReader=newStreamReader(myResponseStream,
Encoding.GetEncoding("utf-8"));
//返回容
stringretString=myStreamReader.ReadToEnd();
returnretString;
}
///
///组装普通文本请求参数。
///
///Key-Value形式请求参数字典
///编码后的请求数据
staticstringBuildQuery(IDictionaryparameters,stringencode)
StringBuilderpostData=newStringBuilder();
boolhasParam=false;
lEnumerator>dem=parameters.GetEnumerator();
while(dem.MoveNext())
{
stringname=dem.Current.Key;
stringvalue=dem.Current.Value;
if
(!
string.lsNullOrEmpty(name))//&&!
string.lsNullOrEmpty(value)
{
if(hasParam)
{
postData.Append("&”);
}
postData.Append(name);
postData.Append("=");
if(encode=="gb2312")
{
postData.Append(HttpUtility.Encode(value,
Encoding.GetEncoding("gb2312")));
}
elseif(encode=="utf8")
{
postData.Append(HttpUtility.Encode(value,
Encoding.UTF8));
}
else
{
postData.Append(value);
}
hasParam=true;
returnpostData.ToString();
///
///把响应流转换为文本。
///
///vparamname="rsp">响应流对象
///vparamname="encoding">编码方式
///vreturns>响应文本
staticstringGetResponseAsString(HttpWebResponsersp,Encodingencoding)
{
System.IO.Streamstream=null;
StreamReaderreader=null;
try
{
//以字符流的方式读取HTTH向应
stream=rsp.GetResponseStream();
reader=newStreamReader(stream,encoding);
returnreader.ReadToEnd();
}
finally
{
//释放资源
if(reader!
=null)reader.Close();
if(stream!
=null)stream.Close();
if(rsp!
=nuII)rsp.Close();
}
}
}
[代码][PHP]代码
*c远程传输工具
*/
publicfunctionpost_c($,$body,$header,$type='POST'){
$ch=c_init();
c_setopt($ch,COPT_,$);
c_setopt($ch,COPT_HEADER,0);//0只要正文
c_setopt($ch,COPT_TIMEOUT,5);〃设置超时时间
c_setopt($ch,COPT_CONNECTTIMEOUT,5);
//将c_exec()获取的信息以文件流的形式返回,而不是直接输出。
c_setopt($ch,COPT_RETURNTRANSFER,1);
//增加header头信息
//array_push($header,'Accept:
application/json');
//array_push($header,'Content-Type:
application/json');
//array_push($header,'http:
multipart/form-data');
if(count($body)>0){
c_setopt($ch,COPT_POSTFIELDS,$body);
}
if(count($header)>0){
c_setopt($ch,COPT_HTTPHEADER,$header);
}
//设置上传文件相关
c_setopt($ch,COPT_FOLLOWLOCATION,true);
c_setopt($ch,COPT_MAXREDIRS,3);〃递归
c_setopt($ch,COPT_SSL_VERIFYPEER,false);〃对认证证书来源的检查
c_setopt($ch,COPT_SSL_VERIFYHOST,0);〃从证书中检查SSL加密算法
switch($type){
case'GET':
c_setopt($ch,COPT_HTTPGET,1);
break;
case'POST':
c_setopt($ch,COPT_POST,1);
break;
case'PUT':
c_setopt($ch,COPT_CUSTOMREQUEST,'PUT');
break;
case'DELETE':
c_setopt($ch,COPT_CUSTOMREQUEST,'DELETE');
break;
}