目的是通过socket实现python和Geant4应用的通信,把Geant的模拟数据传送给python。在下面的试验中python作为服务端,Geant4作为客户端,运行环境为windows+vc2015。
一、c++客户端
PNClient.hh
#ifndef PNClient_H
#define PNClient_H 1
#include <string>
#include <Winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#pragma warning(disable:4996)
class PNClient {
public:
PNClient();
~PNClient();
void Close();
void SendLine(std::string);
std::string ReceiveLine();
int Send(char*, int);
int Receive(char*);
private:
SOCKET s_;
static void Start();
static void End();
};
#endif
PNClient.cc
#include "PNClient.hh"
#include <iostream>
PNClient::~PNClient()
{
End();
}
void PNClient::Start()
{
WSADATA info;
if (WSAStartup(MAKEWORD(2,2), &info)) {
throw "Could not start WSA";
}
}
PNClient::PNClient():s_(0)
{
Start();
s_ = socket(AF_INET,SOCK_STREAM,0);
if (s_ == INVALID_SOCKET) {
throw "INVALID_SOCKET";
}
std::string error;
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
memset(&(addr.sin_zero), 0, 8);
if (::connect(s_, (sockaddr *) &addr, sizeof(sockaddr))) {
error = strerror(WSAGetLastError());
throw error;
}
}
std::string PNClient::ReceiveLine() {
std::string ret;
while (1) {
char r;
if(recv(s_, &r,