标签:style os io for 数据 sp on c ad
服务器端
# -*- coding: utf-8 -*-
# python:2.x
__author__ = ‘Administrator‘
from socket import *
from time import *
HOST=‘‘
PORT=1122#侦听端口
BUFSIZ=1024
ADDR=(HOST,PORT)
sock=socket(AF_INET,SOCK_STREAM)
sock.bind(ADDR)
sock.listen(5)
#条件
STOP_CHAT=False
while not STOP_CHAT:
print u‘等待接入,侦听端口:%d‘%(PORT)
tcpClientSock,addr=sock.accept()
print u‘接收,客户端地址:%d‘%(addr)
while True:
try:
data=tcpClientSock.recv(BUFSIZ)#接收数据
except:
tcpClientSock.close()
break
if not data:
break
IOSTIMEFORMAT=‘%Y-%m-%d %X‘
strime=strftime(IOSTIMEFORMAT,localtime())
s=u‘%s发送给我的信息是:%s‘%(addr[0],data.decode(‘utf8‘))
tcpClientSock.send(s.encode(‘utf8‘))
print ([strime],‘:‘,data.decode(‘utf8‘))
#如果输入quit(忽略大小写),则程序退出
STOP_CHAT=(data.decode(‘utf8‘).upper()==‘QUIT‘)
if not STOP_CHAT:
break
tcpClientSock.close()
sock.close()
print ‘-------‘
客户端程序
# -*- coding: utf-8 -*-
# python:2.x
__author__ = ‘Administrator‘
from socket import *
class TcpC:
HOST=‘127.0.0.1‘
PORT=1122
BUFSIZ=2048
ADDR=(HOST,PORT)
def __init__(self):
self.client=socket(AF_INET,SOCK_STREAM)
self.client.connect(self.ADDR)
while True:
data=raw_input(‘>‘)
if not data:
break
self.client.send(data)
print ‘发送信息到%s:%s‘%(self.HOST,data)
if data.upper()==‘QUIT‘:
break
data=self.client.recv(self.BUFSIZ)
if not data:
break
print ‘从%s收到的信息%s‘%(self.HOST,data)
if __name__==‘__main__‘:
client=TcpC()
print ‘udp学习‘
# python:2.x
__author__ = ‘Administrator‘
from socket import *
#upd通讯
port=8081#端口号
s=socket(AF_INET,SO_DEBUG)#发送者,接收udp数据
s.bind((‘‘,port))
print u‘等待数据接收‘
while True:
#接收数据
data,addr=s.recvfrom()
print ‘received:‘,data,‘from:‘,addr
# -*- coding: utf-8 -*-
# python:2.x
__author__ = ‘Administrator‘
from socket import *
#upd通讯
port=8081#端口号
host=‘localhost‘
s=socket(AF_INET,SOCK_DGRAM)
s.sendto(b‘hello,this is a test info!‘,(host,port))
Python Socket基础学习,注意,需要先开服务器程序,在开客户端程序,
标签:style os io for 数据 sp on c ad
原文地址:http://www.cnblogs.com/mhxy13867806343/p/3956598.html