一、服务端使用了Protocol和LineReceiver方式,代码如下:
-
#coding=utf-8
-
from twisted.internet import reactor
-
from twisted.internet.protocol import Protocol,Factory
-
from twisted.protocols.basic import LineReceiver
-
-
class SimpleLogger(Protocol):
-
def connectionMade(self):
-
print u'客户端的IP和端口号为:',self.transport.client
-
-
def connectionLost(self,reason):
-
print self.transport.client,u'客户端断开'
-
-
def dataReceived(self,data):
-
print str(data)
-
self.transport.write('Client how are you')
-
-
class SimpleLoggerLineRece(LineReceiver):
-
def connectionMade(self):
-
print u'客户端的IP和端口号为:',self.transport.client
-
-
def connectionLost(self,reason):
-
print self.transport.client,u'客户端断开'
-
-
def lineReceived(self,line):
-
print 'line'
-
print line
-
-
def dataReceived(self,data):
-
print str(data)
-
self.transport.write('Client how are you')
-
-
def rawDataReceived(self,data):
-
print 'rawData'
-
print data
-
-
def sendLine(self,line):
-
self.transport.write('Client how are you')
-
-
-
factory=Factory()
-
#factory.protocol=SimpleLogger
-
factory.protocol=SimpleLoggerLineRece
-
-
reactor.listenTCP(1234,factory)
-
reactor.run()
二、客户端代码只是简单的用python自带的socket实现发送和接收的,代码如下:
-
#coding=utf-8
-
import socket
-
s=socket.socket()
-
host="127.0.0.1"
-
port=1234
-
s.connect((host,port))
-
s.send('Server how are you')
-
print s.recv(1024)
-
s.close()
阅读(1892) | 评论(0) | 转发(0) |