利用socket实现python与C++连续通信

python中socket的使用介绍可以参看下面这个博客https://www.cnblogs.com/aylin/p/5572104.html

我的实验示例直接上代码,实验后可持续通信运行

python(python版本3.6.4)作为服务器端:

import socket
import time

if __name__ == '__main__':
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(("localhost", 8888))
    server.listen(0)
    connection, address = server.accept()
    print(connection, address)
    num=0
    while True:
        # connection, address = server.accept()
        # print(connection, address)

        recv_str=connection.recv(1024)[0:5]
        print("enter 1")
        recv_str=recv_str.decode("ascii")
        if not recv_str:
            break
        num=num+1
        print( recv_str,num)

        connection.send( bytes("clientRecv: %s," % recv_str,encoding="ascii"))
        time.sleep( 0.5 )


    connection.close()
    input("enter end")

 

C++(VS2015)作为客户端:

#include   
#include   
#pragma comment(lib,"ws2_32.lib")
#pragma warning(disable:4996)
#include 

int main()
{
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;

	wVersionRequested = MAKEWORD(1, 1);

	err = WSAStartup(wVersionRequested, &wsaData);
	if (err != 0) {
		return -1;
	}

	if (LOBYTE(wsaData.wVersion) != 1 ||
		HIBYTE(wsaData.wVersion) != 1) {
		WSACleanup();
		return -1;
	}
	SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);

	SOCKADDR_IN addrSrv;
	addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_port = htons(8888);
	connect(sockClient, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
	
	char* baseCh = { "hello" };
	for (int clc = 0; clc < 5; clc++)
	{
		send(sockClient, baseCh, strlen(baseCh) + 1, 0);
		char recvBuf[50];
		recv(sockClient, recvBuf, 50, 0);
		printf("severRecv %s\n", recvBuf);
		char t[2];
		std::cin >> t;
	}

	closesocket(sockClient);
	WSACleanup();

	getchar();
	return 0;
}

先运行服务器端代码,再运行C++客户端代码

 

你可能感兴趣的:(python)