python学习八:网络编程初探

来源:互联网 发布:php导出excel报表 编辑:程序博客网 时间:2024/06/06 16:39
from socket import *HOST = "localhost"PORT = 21567BUFSIZE = 1024ADDR = (HOST, PORT)tcpCliSock = socket(AF_INET, SOCK_STREAM)tcpCliSock.connect(ADDR)while True:data = raw_input('>')if not data:breaktcpCliSock.send(data)data = tcpCliSock.recv(BUFSIZE)if not data:breakprint dataconnSock.close()

from socket import *from time import ctimeHOST = 'localhost'PORT = 21567BUFSIZE = 1024ADDR = (HOST, PORT)tcpSerSock = socket(AF_INET, SOCK_STREAM)tcpSerSock.bind(ADDR)tcpSerSock.listen(5)try:while True:print "waiting for connection..."connSock, addr = tcpSerSock.accept()print "...connect from:", addrwhile True:data = connSock.recv(BUFSIZE)if not data:breakconnSock.send("[%s] %s" % (ctime(), data))connSock.close()except (EOFError, KeyboardInterrupt), e:print "print the error:", etcpSerSock.close()

from twisted.internet import protocol, reactorHOST = 'localhost'PORT = 21567class TSClntProtocol(protocol.Protocol):def sendData(self):data = raw_input('>')if data:print '...sending %s...' %dataself.transport.write(data)else:self.transport.loseConnection()def connectionMade(self):self.sendData()def dataReceived(self, data):print dataself.sendData()class TSClntFactory(protocol.ClientFactory):protocol = TSClntProtocolclientConnectionLost = clientConnectionFailed = \lambda self, connector, reason: reactor.stop()reactor.connectTCP(HOST, PORT, TSClntFactory())reactor.run()

from twisted.internet import protocol, reactorfrom time import ctimePORT = 21567class TSServProtocol(protocol, Protocol):def connectionMade(self):clnt = self.clnt = self.transport.getPeer().hostprint '...connected from:', clntdef dataReceived(self, data):self.transport.write('[%s] %s' % (ctime(), data))factory = protocol.Factory()factory.protocol = TSServProtocolprint "waiting for connection..."reactor.listenTCP(PORT, factory)reactor.run()


原创粉丝点击