Skip to content

Instantly share code, notes, and snippets.

@denik
Last active February 17, 2017 18:05
Show Gist options
  • Save denik/8c4fcf4593ced686c718 to your computer and use it in GitHub Desktop.
Save denik/8c4fcf4593ced686c718 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
import sys
class EchoClient(LineReceiver):
end="Bye-bye!"
def connectionMade(self):
self.sendLine("Hello, world!")
self.sendLine("What a fine day it is.")
self.sendLine(self.end)
def lineReceived(self, line):
print "receive:", line
if line==self.end:
self.transport.loseConnection()
class EchoClientFactory(ClientFactory):
protocol = EchoClient
def clientConnectionFailed(self, connector, reason):
print 'connection failed:', reason.getErrorMessage()
reactor.stop()
def clientConnectionLost(self, connector, reason):
print 'connection lost:', reason.getErrorMessage()
reactor.stop()
def main():
factory = EchoClientFactory()
reactor.connectTCP('localhost', 8000, factory)
reactor.run()
if __name__ == '__main__':
main()
from gevent import socket
end = "Bye-bye!\n"
conn = socket.create_connection(('localhost', 8000))
conn.sendall("Hello, world\n")
conn.sendall("What a fine day it is.\n")
conn.sendall(end)
for line in conn.makefile():
if line == end:
conn.close()
break
# explicit error handling is not needed as exceptions will be raised in case of errors
# normal try/except/finally/else mechanism is available to manage them
@denik
Copy link
Author

denik commented May 3, 2014

Sorry, actually I haven't. Updated to run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment