基于tcp协议的socketserver
server:
#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/5/7
# 服务端特点是:
# 1 一直运行提供服务(链接循环)(基于一个链接通信循环)
# 2 绑定一个唯一的地址
# import socket
# phone = socket.socket()
# phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) # 端口重用
# phone.bind(('127.0.0.1',8080))
# phone.listen(5)
# conn,addr = phone.accept()
# while True:
# print(conn)
# msg = input('>>: ')
# conn.send(msg.encode())
import socketserver
class FTPServer(socketserver.BaseRequestHandler):
def handle(self):
print(self.request)
while True:
data = self.request.recv(1024)
print(data)
self.request.send(data.upper())
if __name__ =='__main__':
obj = socketserver.ThreadingTCPServer(('127.0.0.1',8081),FTPServer)
obj.serve_forever() # 链接循环(多线程)
client1:
#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/5/7
import socket
phone = socket.socket()
phone.connect(('127.0.0.1', 8081))
while True:
msg = input('>>: ')
phone.send(msg.encode('utf-8'))
data = phone.recv(1024)
print(data)
client2:
#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/5/7
import socket
phone = socket.socket()
phone.connect(('127.0.0.1', 8081))
while True:
msg = input('>>: ')
phone.send(msg.encode('utf-8'))
data = phone.recv(1024)
print(data)