【整理】Python Socket Server with C++ Socket Client通信

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【整理】Python Socket Server with C++ Socket Client通信

Python与C++通信,早前博客(【整理】Linux Socket网络编程_TCP编程(4)_C++与PythonSocket通信)有一篇是:C++做服务端,Python做客户端,这一篇正好相反。

方法大同小异,在此提供示例代码以及下载

Python服务端:

python_server.py:

# -*- coding: utf-8 -*-
import socket

#创建一个socket对象
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
#sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 0)
#sock.setblocking(1)
ip_port = ('127.0.0.1',9998)
#绑定ip和端口号
sock.bind(ip_port)
#sock.setblocking(1)
#设置最大连接数
sock.listen(5)


while True:
	#使用accept方法获取一个客户端连接
	#获取客户端的scoket对象conn和客户端的地址(ip、端口号)address
	conn,address = sock.accept()
	# 给客户端发信息
	send_data = 'Hello.'
	conn.sendall(send_data)
	while True:
		try:
			# 接收客户端消息
			recv_data = conn.recv(1024)
			#print 'Client:', recv_data, ", Type:", type(recv_data), ", Equal:", (recv_data.replace("0x00", "") == 'start')
			#print 'Client:', recv_data[0:5], ", Type:", type(recv_data[0:5])
			# 如果收到start就开始调用统计代码
			if recv_data[0:5] == 'start':
				print 'Ok, Starting...'
				# 开始调用统计代码输出结果到变量 result
				pass	
			#检测客户端发出退出指令,关闭连接
			if recv_data[0:4] == 'exit':
				break
			#s = input('Server:').strip()
			#if len(s) == 0:
			#	break
			#conn.send(bytes(s,encoding='utf-8'))
		except Exception as e:
			break

	# 关闭客户端的socket连接
	conn.close()

 

运行指令:

python python_server.py

 

C语言客户端代码:

socket_client.c

#include <netdb.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <memory.h>
#include <signal.h>
#include <time.h>

int main() {


	/*步骤1:创建socket*/
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);

	if (sockfd < 0) {
		perror("socket error");
		exit(1);
	}


	struct sockaddr_in serveraddr;
	memset(&serveraddr, 0, sizeof(serveraddr));
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(atoi("9998"));
	inet_pton(AF_INET, "127.0.0.1", &serveraddr.sin_addr.s_addr);

	/*步骤2:客户端调用connect函数连接到服务器*/
	if (connect(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) {
		perror("connect error");	
		exit(1);
	}

	/*步骤3:调用IO函数(read/write)进行服务端的双向通信*/
	char buffer[1024];
	memset(buffer, 0, sizeof(buffer));
	strcpy(buffer, "start");

	size_t size;

	/*if ((size = read(sockfd, buffer, sizeof(buffer))) < 0) {
		perror("read error");	
	}*/

	printf("buffer is %s, sizeof(buffer) is %d\n", buffer, sizeof(buffer));

	if (write(sockfd, buffer, sizeof(buffer)) < 0) {
		perror("write error");	
	}

	/*步骤4:关闭socket*/
	close(sockfd);
	
	return 0;
}

编译指令:

gcc socket_client.c -o socket_client

运行指令:

./socket_client

演示效果:

python_server_cpp_client

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【整理】Python Socket Server with C++ Socket Client通信

文章的脚注信息由WordPress的wp-posturl插件自动生成



|2|left
打赏

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: