首页 > 代码库 > python简单C/S模式示例
python简单C/S模式示例
服务器端代码:
1 #!/usr/bin/python 2 3 import time, socket, threading 4 5 # thread handle function 6 def tcplink(sock, addr): 7 print ‘Accept new connection from %s:%s...‘ % addr 8 sock.send(‘Welcome!‘) 9 while True:10 data = http://www.mamicode.com/sock.recv(1024)11 time.sleep(1)12 if data =http://www.mamicode.com/= ‘exit‘ or not data:13 break14 sock.send(‘Hello, %s!‘ % data)15 sock.close()16 print ‘Connection from %s:%s closed.‘ % addr17 18 # create socket object19 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)20 # listen port21 s.bind((‘127.0.0.1‘, 9999))22 # start listen23 s.listen(5)24 # print prompt25 print ‘Waiting for connection...‘26 27 while True:28 # accept a new connection29 sock, addr = s.accept()30 # create new thread to handle tcp connection31 t = threading.Thread(target=tcplink, args=(sock, addr))32 t.start()33 34
客户端代码:
1 #!/usr/bin/python 2 3 # import module 4 import socket 5 6 # create TCP object 7 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 # connect sina 9 s.connect((‘127.0.0.1‘, 9999))10 # receive welcome11 print s.recv(1024)12 13 for data in [‘zjw‘, ‘ygl‘, ‘lele‘]:14 # send data15 s.send(data)16 print s.recv(1024)17 while True:18 data = http://www.mamicode.com/1
设计思路还是那样的,服务器端监听固定端口,等待连接,客户端来连接,然后互相发送消息
python简单C/S模式示例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。