C++的TCP server + Python显示

TCP:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <netinet/in.h>

const int server_port = 8080;
const char* server_ip = "10.3.18.22";

int main()
{

    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(sock_fd < 0)
    {
        perror("socket");
        return 1;
    }
    else printf("success to create sock_fd\n");

    // set address
    struct sockaddr_in socket_addr;
    socket_addr.sin_family = AF_INET;
    socket_addr.sin_port = htons(server_port);
    socket_addr.sin_addr.s_addr = inet_addr(server_ip);
    if(bind(sock_fd, (struct sockaddr*)&socket_addr, sizeof(sockaddr_in)) < 0)
    {
        perror("bind");
        return 2;
    }
    else printf("success to bind sock_fd\n");

    // listen socket
    int listen_sock = listen(sock_fd, 5);
    if(listen_sock < 0)
    {
        perror("listen");
        return 3;
    }
    else printf("success to listen sock_fd\n");

    // ready to accept
    struct sockaddr_in peer;
    socklen_t peer_len;
    char ctl_buf[1024];
    short *trans_buf;
    int accept_fd = accept(sock_fd, (struct sockaddr*)&peer, &peer_len);
    if(accept_fd < 0)
    {
        perror("accept");
        return 4;
    }
    else
    {
        printf("connected with ip: %s and port: %d\n", inet_ntop(AF_INET, &peer.sin_addr, ctl_buf, 1024), ntohs(peer.sin_port));
    }

    int i, recv_cnt = 0;
    while(1)
    {
        memset(ctl_buf, '\0', sizeof(ctl_buf));

        ssize_t size = read(accept_fd, ctl_buf, sizeof(ctl_buf));
        printf("size: %ld\n", size);
        printf("ctl_buf: %s\n", ctl_buf);
        if(0 < size)
        {
            recv_cnt = atoi(ctl_buf);
            printf("request data num is: %d\n", recv_cnt);
        }
        else
        {
            perror("read");
            break;
        }

        if(0 == recv_cnt) {
            printf("request data is over\n");
            break;
        }
        else {
            trans_buf = (short *)malloc(recv_cnt * sizeof(short));
            if(NULL == trans_buf) {
                printf("malloc failed\n");
                break;
            }
            for(i=0;i<recv_cnt;i++) trans_buf[i] = i;
            write(accept_fd, trans_buf, recv_cnt * sizeof(short));
            printf("send %d shorts\n", recv_cnt);
        }

    }

    close(sock_fd);

    printf("sock_fd is closed\n");

    return 0;
}

Python:

import threading
import time
import numpy as np
from matplotlib import pyplot as plt
from socket import *
import sys

tcp_client_socket = socket(AF_INET, SOCK_STREAM)
server_ip = "10.3.18.22"
server_port = int("8080")
tcp_client_socket.connect((server_ip, server_port))

total_num = 1000 * 200
cell_num = 512

class the_obtainer(threading.Thread):
   def __init__(self, threadID, name, lock_cnt):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.lock_cnt = lock_cnt
   def run(self):
      print("Starting " + self.name)
      # obtain
      while True:
         if 0 == self.lock_cnt:
            threadLock_0.acquire()
            data_obtain(self.lock_cnt)
            threadLock_0.release()
            # print("data_obtain once")
            self.lock_cnt = 1 - self.lock_cnt
         else:
            threadLock_1.acquire()
            data_obtain(self.lock_cnt)
            threadLock_1.release()
            # print("data_obtain once")
            self.lock_cnt = 1 - self.lock_cnt

class the_consumer(threading.Thread):
   def __init__(self, threadID, name, lock_cnt):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.lock_cnt = lock_cnt
   def run(self):
      print("Starting " + self.name)
      time.sleep(0.01)
      while True:
         if 0 == self.lock_cnt:
            threadLock_0.acquire()
            data_plot(self.lock_cnt)
            threadLock_0.release()
            # print("data_plot once")
            self.lock_cnt = 1 - self.lock_cnt
         else:
            threadLock_1.acquire()
            data_plot(self.lock_cnt)
            threadLock_1.release()
            # print("data_plot once")
            self.lock_cnt = 1 - self.lock_cnt
         # print(time.localtime())

def data_obtain(lock_cnt):
   global data_0
   global data_1
   send_ctl = "%d" %total_num
   tcp_client_socket.send(send_ctl.encode("gbk"))
   total_cnt = total_num * 2
   is_first = 1
   while total_cnt > 0:
      if total_cnt < (cell_num*2):
         recvData = tcp_client_socket.recv(total_cnt)
      else:
         recvData = tcp_client_socket.recv(cell_num*2)
      total_cnt = total_cnt - len(recvData)

      if 1 == is_first:
         is_first = 0
         tmp_data = recvData
      else:
         tmp_data = tmp_data + recvData
   byte_num = len(tmp_data)
   if (total_num*2) != byte_num:
      print("byte_num is unnormal")
      print(byte_num)
      exit()
   if 0 == lock_cnt:
      data_0 = np.frombuffer(tmp_data, dtype=np.int16)
      data_num = len(data_0)
   else:
      data_1 = np.frombuffer(tmp_data, dtype=np.int16)
      data_num = len(data_1)
   if total_num != data_num:
      print("data_num is unnormal")
      print(data_num)
      exit()

def data_plot(lock_cnt):
   global data_0
   global data_1
   x = np.arange(0, total_num)
   if 0 == lock_cnt:
      plt.plot(x, data_0, 'g')
   else:
      plt.plot(x, data_1, 'y')
   plt.draw()
   plt.pause(0.0001)

# initial
threadLock_0 = threading.Lock()
threadLock_1 = threading.Lock()
thread_0 = the_obtainer(0, "the_obtainer", 0)
thread_1 = the_consumer(1, "the_consumer", 0)
data_0 = []
data_1 = []

# run
thread_0.start()
thread_1.start()

# exit
threads = []
threads.append(thread_0)
threads.append(thread_1)
for t in threads:
   t.join()
print("Exiting Main Thread")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值