socket参数应用介绍
基础版套接字通信
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 17/11/7 15:26# @Author : Tiancc# @Site : # @File : Server.py# @Software: PyCharmfrom socket import *cmd=socket(socket.AF_INET,socket.SOCK_STREAM) #等同于socker()#SOCK_STREAM 代表TCP协议(流式协议),SOCK_DGRAM代表UDP协议(数据包协议)cmd.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) #重用准备被回收的端口(短时间内)1为开启cmd.bind(('127.0.0.1',8080)) #本地地址以及端口cmd.listen(3) #最大挂起的链接数n,client_addr = cmd.accept() #(套接字链接,客户端的IP合端口)while True: coon, client_addr = cmd.accept() # 套接字链接,客户端的IP合port while True: try: data = coon.recv(1024) # 收消息 1024字节 print('客户端数据: ', data.decode('utf-8')) if not data: break # MAC Linux 断开后的处理 coon.send(data.upper()) # 发消息 except Exception: break coon.close()cmd.close()
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 17/11/7 15:26# @Author : Tiancc# @Site : # @File : Client.py# @Software: PyCharmfrom socket import *cmd = socket()cmd.connect(('127.0.0.1',8080))while True: _input = input('>>: ').strip() if not _input:continue #判断用户不可以输入空,因为操作系统内存不会发空 cmd.send(_input.encode('utf-8')) #发消息 data = cmd.recv(1024) #收消息 print(data.decode('utf-8'))cmd.close()
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 17/11/7 17:25# @Author : Tiancc# @Site : # @File : Client2.py# @Software: PyCharmfrom socket import *cmd = socket()cmd.connect(('127.0.0.1',8080))while True: _input = input('>>: ').strip() if not _input:continue cmd.send(_input.encode('utf-8')) #发消息 data = cmd.recv(1024) #收消息 print(data.decode('utf-8'))cmd.close()