我是靠谱客的博主 昏睡蚂蚁,最近开发中收集的这篇文章主要介绍python c++ socket 通信一个示例1 作用说明2 代码3 结果,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

目录

1 作用说明

2 代码

2.1 客户端client ( c++ boost::asio)

main.cpp

CMakelists.txt

2.2 服务端server (python socket )

3 结果

client

server


1 作用说明

  • 客户端: 连续发送n个字符串消息 ("client_msg_n"),
  • 服务端: 处理客户端消息, 返回对应的字符串信息("client_msg_n<<handled")

2 代码

2.1 客户端client ( c++ boost::asio)

main.cpp

#include <iostream>
#include <boost/asio.hpp>

using namespace std;

//client
int main(int argc, char **argv) {
    try
    {
        cout << "client start...." << endl;
        //io_service对象
        boost::asio::io_service ios;
        //创建socket对象
        boost::asio::ip::tcp::socket sock(ios);
        //创建连接端
        boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"),6783);
        //连接
        sock.connect(ep);
        //定义一个缓冲区
        //char data[128];
        char msgToServer[256];
        char msgFromServer[256];
        for(int i = 0; i<3; i++)
        {
            std::memset(msgToServer, 0, sizeof(msgToServer));
            std::memset(msgFromServer, 0, sizeof(msgFromServer));
            
            string tmp = "client_msg_" + to_string(i);
            strcpy(msgToServer, tmp.c_str());
            
            cout << "msgToServer: " << msgToServer <<endl;

            //boost::asio::write(sock,boost::asio::buffer(msgToServer));
            sock.send(boost::asio::buffer(msgToServer));
            
            // writing server dealing with the message...

            //boost::asio::read(sock,boost::asio::buffer(msgFromServer));
            sock.receive(boost::asio::buffer(msgFromServer));
            cout << "dataHandled: " << msgFromServer << endl; 
            
            sleep(1);
        }
        
        sock.send(boost::asio::buffer("quit_client"));
        //sock.send(boost::asio::buffer("quit_server"));
    }
    catch (exception& e)
    {
        cout << e.what()<< endl;
    }
    std::cout << "Hello, world!" << std::endl;
    return 0;
}

CMakelists.txt

cmake_minimum_required(VERSION 2.6)
project(socket_test)

SET(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11")
find_package( Boost REQUIRED  system)

if(NOT Boost_FOUND)
    message("Not found Boost")
endif()

include_directories(${Boost_INCLUDE_DIRS})


add_executable(socket_test main.cpp)


target_link_libraries(socket_test ${Boost_LIBRARIES})

target_link_libraries(${PROJECT_NAME}
-pthread
)


install(TARGETS socket_test RUNTIME DESTINATION bin)

2.2 服务端server (python socket )

import socket
#import json
import time
import os
import sys
#import threading

host = '127.0.0.1'
port = 6783

class SocketServer:
    def __init__(self):
        print("> server start.... ")
        socketer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # set the port reuesd
        socketer.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        socketer.bind((host, port))
        # define the max connection
        socketer.listen(10)
        self.sock = socketer

    def start_server(self):  
        while True:
            print("> waiting for connection....")
            client, address = self.sock.accept()
            print("> new connection :  IP: {0}; Port:{1} ".format(address[0],address[1]))
            #t = threading.Thread(target=self.client_recv,args=(client,address))
            #t.start()
            self.client_recv(client, address)
            print(">  -------Done for this client. -------")

    def client_recv(self, client, address):
        while True:
            # read message from socket
            msg = client.recv(1024).decode("utf-8") #client_msg_0x00x00x00x00x00...
            msg = msg.rstrip("x00")
            if msg == '':
                return 
            if msg == "EOF":
                return 
            elif msg == "quit_client":
                client.close()
                #self.sock.close()
                print("> client  exit...")
                return
            elif msg == "quit_server":
                client.close()
                self.sock.close()
                print("> server  exit...")
                sys.exit(0)
            else:
                print ("> -------", time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),"-------")            
                print("> receive the msg from client : {0}".format(msg))
                #TODO:

                print('> do sth for {0}'.format(msg))   
                result = msg + "<<handled"
                client.send(result.encode(encoding='utf-8'))
                print("> send the responce back to client: {0}".format(result))
        return

if __name__ == '__main__':
    t = SocketServer()
    t.start_server()

3 结果

client

client start....
msgToServer: client_msg_0
dataHandled: client_msg_0<<handled
msgToServer: client_msg_1
dataHandled: client_msg_1<<handled
msgToServer: client_msg_2
dataHandled: client_msg_2<<handled
Hello, world!
*** Finished ***

server

> server start.... 
> waiting for connection....
> new connection :  IP: 127.0.0.1; Port:43956 
> ------- 2020-11-21 10:37:07 -------
> receive the msg from client : client_msg_0
> do sth for client_msg_0
> send the responce back to client: client_msg_0<<handled
> ------- 2020-11-21 10:37:08 -------
> receive the msg from client : client_msg_1
> do sth for client_msg_1
> send the responce back to client: client_msg_1<<handled
> ------- 2020-11-21 10:37:09 -------
> receive the msg from client : client_msg_2
> do sth for client_msg_2
> send the responce back to client: client_msg_2<<handled
> client  exit...
>  -------Done for this client. -------
> waiting for connection....

最后

以上就是昏睡蚂蚁为你收集整理的python c++ socket 通信一个示例1 作用说明2 代码3 结果的全部内容,希望文章能够帮你解决python c++ socket 通信一个示例1 作用说明2 代码3 结果所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部