客户端的例子过程比较简单
1、先建立Socket
2、建立connect
3、接收/发送
注意是接收是阻塞模式
客户端代码:
ChatClient.cpp
/*
* ChatClient.cpp
*
* Created on: 2012-9-29
* Author: root
*/
#include "ClientSocket.h"
#include "SocketException.h"
#include <string>
#include <iostream>
#include "Encoder.h"
#include "Decoder.h"
using namespace std;
int main() {
cout << "====Running Client...====" << endl;
try{
std::string strValue = "{\"action\":\"Test\"}";
ClientSocket clientSocket("127.0.0.1",888000);
// string massage=Encoder::encoder(strValue);
// cout << Decoder::decoder(massage) << endl;
while(1){
// clientSocket.Recevie(massage);
// cout << "Response from server:" << massage << endl;
// massage.clear();
clientSocket.Send(Encoder::encoder(strValue));
sleep(5);
}
}catch (SocketException& e) {
cout << "Exception was caught:" << e.DisplayMsg() << endl;
}
return 0;
}
解析数据是必需的,因为Socket机制会优先发送的机制,从而导致粘包现在(将两次小数据当作一次来),其中有两种解决方法,一种是设置setsocketopt,不支持nagle算法,第二就是进行对包封装,一般是计算数据长度,并加入到包头,解析时就先解析包头的长度,接下来就一直接收到该 长度就可得到“刚好”的数据
/*
* Decoder.h
*
* Created on: 2012-10-18
* Author: root
*/
#ifndef DECODER_H_
#define DECODER_H_
#include <string>
class Decoder {
public:
Decoder();
virtual ~Decoder();
static std::string decoder(std::string message);
};
#endif /* DECODER_H_ */
Decoder.cpp 解析数据实现类
/*
* Decoder.cpp
*
* Created on: 2012-10-18
* Author: root
*/
#include "Decoder.h"
#include "TypeConvert.h"
Decoder::Decoder() {
}
Decoder::~Decoder() {
}
std::string Decoder::decoder(std::string message) {
int length = message.length();
if (length <= 4) {
return ""; // waite
}
std::string datalengstr = message.substr(0, 4);
int dataleng = TypeConvert::Strint2Int(datalengstr);
if (dataleng > length - 4) {
return "";
}
return message.substr(4, length - 4);
}
Encoder.h 加密数据
/*
* Encoder.h
*
* Created on: 2012-10-18
* Author: root
*/
#ifndef ENCODER_H_
#define ENCODER_H_
#include <string>
class Encoder {
public:
Encoder();
virtual ~Encoder();
static std::string encoder(std::string message);
};
#endif /* ENCODER_H_ */
Encoder.cpp 加密数据类
/*
* Encoder.cpp
*
* Created on: 2012-10-18
* Author: root
*/
#include "Encoder.h"
#include "TypeConvert.h"
#include <iostream>
Encoder::Encoder() {
// TODO Auto-generated constructor stub
}
Encoder::~Encoder() {
// TODO Auto-generated destructor stub
}
std::string Encoder::encoder(std::string message) {
int length = message.length();
std::string lenstr = TypeConvert::Int2String(length);
if (length < 10) {
lenstr = "000" + lenstr;
} else if (length < 100) {
lenstr = "00" + lenstr;
} else if (length < 1000) {
lenstr = "0" + lenstr;
}
return (lenstr + message);
}