python实现简单的客服端/服务器连接(TCP)

本文介绍了一个简单的TCP套接字编程实例,包括服务端和客户端的创建过程。服务端监听指定端口并接收客户端消息,客户端则连接到服务端并发送消息。通过这个例子可以了解基本的网络通信原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

服务端:

# -*- coding:utf-8 -*-
""" 
created on 2019-07-09
author swen
file read/write
网络编程:服务器TCP套接字创建
"""
from socket import *
from time import ctime
addr=('',23356)
BUFSIZE=1024
tcpSerSoc=socket()
tcpSerSoc.bind(addr)
tcpSerSoc.listen(5)
while True:
	#TCP等待的是一个连接进来,UDP等到四信息直接进来
	print '...waiting connect...:'
	tcpCltSoc,addr=tcpSerSoc.accept()
	print '...connect from...:',addr
	while True:
		data=tcpCltSoc.recv(BUFSIZE)
		if not data:
			break
		tcpCltSoc.send('[%s]%s'%(ctime(),data))
	tcpCltSoc.close()
tcpSerSoc.close()

客户端:

# -*- coding:utf-8 -*-
""" 
created on 2019-07-09

author swen

file read/write

网络编程:客户端TCP套接字创建

"""
from socket import * 
addr=('localhost',23356)
BUFSIZE=1024
tcpCltSoc=socket()
tcpCltSoc.connect(addr)
while True:
	data=raw_input('>')
	if not data:
		break
	tcpCltSoc.send(data)
	data=tcpCltSoc.recv(BUFSIZE)
	if not data:
		break
	print data
tcpCltSoc.close()

[参考]Python核心编程(第二版).pdf

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值