python套接字发送消息,但只有一次可以检索

时间:2017-09-15 16:32:31

标签: python linux sockets

我有一个python套接字客户端示例,我想连接到套接字服务器并发送命令以获取结果。当我使用以下客户端python时 代码,只有第一个命令会成功返回,从第二个命令返回数据长度总是为0。

这是我的调用过程:我将首先导入以下python类,并将其声明为cu = command_util(ip,port),使用cu.execute_command("cmd_name")来执行。在我的申请中,我将运行50次execute_command()

以前,我创建了新的套接字类并先连接,然后使用send()命令,但是当执行这么多命令时,某些结果将会丢失。这就是我需要更改以下代码的原因,这可能会阻止这么多命令。

当前设计python示例:

import sys
from socket import *
import time
import re


class CommandUtil:
    def __init__(self, _host_ip='127.0.0.1', _host_port=2888, _buf_size=4096):
        self._host_ip = _host_ip
        self._host_port = _host_port
        self._buf_size = _buf_size
        _addr = (_host_ip, int(_host_port))
        self._client = socket(AF_INET, SOCK_STREAM)
        self._client.connect(_addr)

    def __del__(self):
        print "enter into __del__"
        self._client.close()

    def execute_command(self, _cmd_str):
        self._client.send(_cmd_str)
        _result = ""
        data = self._client.recv(self._buf_size)
        # debug
        print ("data length=%s " % len(data))
        data_again = ''
        if len(data) < 5 :
            data_again = self._client.recv(self._buf_size)
            print ("data length again=%s " % len(data_again))
        data += data_again
        _result += data[4:]
        if not data:
            print("anything wrong for set %s ?", _cmd_str)
        while len(data) - self._buf_size >= 0:
            # still need to receive data
            data = self._client.recv(self._buf_size)
            _result += data
        return _result

以前为每个命令连接的示例代码:

def execute_command():
    _addr = (_host, int(_port))
    _client = socket(AF_INET, SOCK_STREAM)
    _client.connect(_addr)
    _client.send(_cmd_str)
    data = _client.recv(_buf_size)
    # print ("data length=%s " % len(data))
    data_again = ''
    if len(data) < 5:
        data_again = _client.recv(_buf_size)
        # print ("data length again=%s " % len(data_again))
    data += data_again
    _result += data[4:]
    if not data:
        print("anything wrong for set %s", _cmd_str)
    while len(data) - _buf_size >= 0:
        # still need to receive data
        data = _client.recv(_buf_size)
        _result += data
    _client.close()
    # time.sleep(1)
    return _result

这是c ++中的服务器代码:

struct sockaddr_in ServerAddr;
bzero(&ServerAddr,sizeof(ServerAddr));
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_addr.s_addr = htons(INADDR_ANY);
ServerAddr.sin_port = htons(SERVER_PORT);

int ServerSocket = socket(PF_INET,SOCK_STREAM,0);
int opt =1;
setsockopt(ServerSocket,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
bind(ServerSocket,(struct sockaddr*)&ServerAddr,sizeof(ServerAddr)
listen(ServerSocket, MAX_LISTEN_QUEUE)

char ReqBuff[BUFFER_SIZE];
char RspBuff[BUFFER_SIZE];
while (true) {  #<<<---- Server holder init here !
    struct sockaddr_in ClientAddr;
    socklen_t len = sizeof(ClientAddr);

    int SessionSocket = accept(ServerSocket,(struct sockaddr*)&ClientAddr,&len);

    bzero(ReqBuff, BUFFER_SIZE);
    int length = recv(SessionSocket,ReqBuff,BUFFER_SIZE,0);
    if (length > 0) {
        ReqBuff[length] = '\0';
        std::string Rsp = execcommd()
        if (Rsp.length() == 0) {
            Rsp = "\n";
        }
        bzero(RspBuff, BUFFER_SIZE);
        *((uint32_t *)RspBuff) = Rsp.length();
        send(SessionSocket,RspBuff,sizeof(uint32_t),0)

        uint32_t Pos = 0;
        do {
            uint32_t Len = ((length - Pos) > BUFFER_SIZE) ? BUFFER_SIZE : (length - Pos);
            bzero(RspBuff, BUFFER_SIZE);
            memcpy(RspBuff, Rsp.c_str()+Pos, Len);
            if(send(SessionSocket,RspBuff,Len,0)<0) {
                std::cout << "Send Response Content Fail" << std::endl;
                break;
            }
            Pos += BUFFER_SIZE;
        } while (length > Pos);
    }
    close(SessionSocket);#<<<---- You close whole server not client socket
}
close(ServerSocket);

0 个答案:

没有答案