本文整理汇总了Python中socket.socket.connect方法的典型用法代码示例。如果您正苦于以下问题:Python socket.connect方法的具体用法?Python socket.connect怎么用?Python socket.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socket.socket
的用法示例。
在下文中一共展示了socket.connect方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_mail
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import connect [as 别名]
def send_mail(sender_address, mail_server, receiver_address, message):
try:
client_socket = Socket(socket.AF_INET, socket.SOCK_STREAM)
# set a 1 second timeout
client_socket.settimeout(1.0)
# connect to mail server
client_socket.connect((mail_server, 25))
def send(string):
"""Helper function: fix newlines, encode and send a string"""
final = string.replace("\n", "\r\n").encode("ascii")
print "Sending " + final + "..."
client_socket.send(final)
return 0
def recv_and_check(expected=250):
"""Helper function: recive reply and check it's ok"""
reply = client_socket.recv(2048)
print "Got: ", reply
code = int(reply.rstrip().split()[0])
if code != expected:
raise Exception(reply)
return 0
# get initial message from server
recv_and_check(220)
# send greeting
send("HELO {}\n".format(sender_address.split("@")[1]))
recv_and_check()
# set sender address
send("MAIL FROM: {}\n".format(sender_address))
recv_and_check()
# set receiver address
send("RCPT TO: {}\n".format(receiver_address))
recv_and_check()
# prepare to send message
send("DATA\n")
recv_and_check(354)
# send the message itself followed by terminator
send("{}\n.\n".format(message))
recv_and_check()
send("QUIT\n")
recv_and_check(221)
finally:
client_socket.close()
return 0
示例2: new
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import connect [as 别名]
def new(cls, host, port, logger=None):
logger = logger or logging.getLogger(__name__)
sock = Socket()
try:
sock.connect((host, port))
except socket.error:
return None
return Connection(sock, logger)
示例3: main
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import connect [as 别名]
def main():
if len(sys.argv) <= 1:
print "You need to specify the url of the application to display."
return
scheme, location = urlparse(sys.argv[1])[0:2]
if scheme != "rtk":
print ("Only rtk:// urls are supported for now. I might add an HTTP " "transport at some point in the future.")
if ":" not in location:
location += ":" + str(DEFAULT_PORT)
host, port = location.split(":")
port = int(port)
socket = Socket()
try:
socket.connect((host, port))
except SocketError, e:
print "Error while connecting: " + str(e)
return
示例4: call
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import connect [as 别名]
def call(self, *args, **kwargs):
"""
Remote call.
"""
socket = Socket(AF_INET, SOCK_STREAM)
socket.connect(self.address)
try:
method = Document()
method.name = self.name
method.args = args
method.kwargs = kwargs
socket.send(method.dump())
reply = socket.recv(4096)
result = Document()
result.load(reply)
return result
finally:
socket.close()
示例5: get_page
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import connect [as 别名]
def get_page(server_address, request_string):
try:
client_socket = Socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((server_address, REMOTE_PORT))
client_socket.send(request_string.encode())
reply = bytes()
while True:
part_body = client_socket.recv(BUFFER_SIZE).decode("utf-8", "ignore")
# print part_body
if not len(part_body):
break
reply += part_body
finally:
client_socket.close()
return reply
示例6: _InProgressSocketManager
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import connect [as 别名]
class _InProgressSocketManager(object):
"""
This class does not actually work right now. It's something that I'm
writing that will some day replace InputThread and OutputThread and allow
Autobus to function using only a single thread for each Bus instance. So
it's a work in progress, and it doesn't actually work right now.
"""
def __init__(self):
# Set up the interrupt socket
interrupt_server = Socket()
interrupt_server.bind(("localhost", 0))
interrupt_server.listen(1)
self.interrupt_writer = Socket()
self.interrupt_writer.setblocking(False)
self.interrupt_writer.connect("localhost", interrupt_server.getsockname()[1])
self.interrupt_reader = interrupt_server.accept()
interrupt_server.shutdown(SHUT_RDWR)
interrupt_server.close()
self.interrupt_reader.setblocking(False)
self.interrupt_writer.setblocking(False)
def loop(self):
pass
def run_sync(self, function, timeout=None):
q = Queue()
@self.run_async
def new_function():
q.put(function())
try:
return q.get(timeout=timeout)
except Empty:
raise exceptions.TimeoutException
def run_async(self, function):
pass
def interrupt(self):
self.interrupt_writer.send(0)
示例7: __init__
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import connect [as 别名]
class GoClient:
def __init__(self, IP='127.0.0.1', port=5005):
self.root = tk.Tk()
self.IP = IP
self.port = port
self.players = []
def start_game(self, player, size):
self.players.append(player)
self.board = Board(size)
print 'beginning game as player %d' % player
self.make_display()
self.gui.start_game()
def made_move(self, i, j):
self.board.place_piece(i, j)
self.gui.made_move()
def passed_turn(self):
self.board.pass_turn()
self.gui.passed_turn()
def game_over(self, score1, score2):
self.gui.set_message('Game Over, Black: %d White: %d' % (score1, score2))
self.board.gameover = True
def on_click(self, i, j):
if self.board.turn in self.players:
self.send('MAKEMOVE %d %d' % (i, j))
# self.receive('MADEMOVE %d %d' % (i, j))
def on_quit(self):
send('QUIT')
self.gui.parent.destroy()
def on_pass(self):
if self.board.turn in self.players:
self.send('PASSTURN')
def run(self):
# self.start_game(1)
# self.start_game(2)
self.connect_to_server()
self.root.title('Python Online Five-In-A-Row')
# root.resizable(0,0)
self.root.mainloop()
# print 'received data:', data
def make_display(self):
self.gui = BoardGui(parent=self.root, board=self.board, players=self.players)
self.gui.on_click.append(self.on_click)
self.gui.on_pass.append(self.on_pass)
self.gui.pack(side='top', fill='both', expand='true', padx=4, pady=4)
def receive(self, data):
print 'receiving [%s]' % data
data = data.split()
if not data:
return
message = data[0]
if message == 'BEGINGAME':
self.start_game(int(data[1]), int(data[2]))
elif message == 'MADEMOVE':
i, j = map(int, data[1:3])
self.made_move(i, j)
elif message == 'PASSEDTURN':
self.passed_turn()
elif message == 'GAMEOVER':
a, b = map(int, data[1:3])
self.game_over(a, b)
def send(self, data):
print 'sending %s' % data
self.skt.send(data)
def connect_to_server(self):
BUFFER_SIZE = 1024
self.skt = Socket(AF_INET, SOCK_STREAM)
self.skt.connect((self.IP, self.port))
self.skt.setblocking(0)
def listen():
try:
data = self.skt.recv(BUFFER_SIZE)
except SocketError:
pass
else:
if not data:
return
for line in data.split('\n'):
self.receive(line)
self.root.after(500, listen)
listen()
示例8: __init__
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import connect [as 别名]
class GoBotClient:
def __init__(self, IP='127.0.0.1', port=5005):
self.IP = IP
self.port = port
self.player = None
self.turn = 2
def start_game(self, player, size):
self.player = player
print 'beginning game as player %d' % player
self.GoBot = GoBot(0 if player == 2 else 1)
if player == 2:
self.make_move('pass')
def made_move(self, i, j):
self.turn = 1 if self.turn == 2 else 2
def passed_turn(self):
self.turn = 1 if self.turn == 2 else 2
def make_move(self, move):
if self.turn == self.player:
if move != 'pass':
gobot_move = self.GoBot.make_move((move[1], move[0]))
else:
gobot_move = self.GoBot.make_move('pass')
self.send('MAKEMOVE %d %d' % (gobot_move[1], gobot_move[0]))
def run(self):
self.connect_to_server()
while True:
if self.listen():
print "Disconnected from server\n"
return
def receive(self, data):
print 'receiving [%s]' % data
data = data.split()
if not data:
return
message = data[0]
if message == 'BEGINGAME':
self.start_game(int(data[1]), int(data[2]))
elif message == 'MADEMOVE':
i, j = map(int, data[1:3])
self.made_move(i, j)
if self.turn == self.player:
self.make_move((i, j))
elif message == 'PASSEDTURN':
self.passed_turn()
if self.turn == self.player:
self.make_move('pass')
elif message == 'GAMEOVER':
a, b = map(int, data[1:3])
self.game_over(a, b)
elif message == 'FINISH':
return True
def send(self, data):
print 'sending %s' % data
self.skt.send(data)
def connect_to_server(self):
BUFFER_SIZE = 1024
self.skt = Socket(AF_INET, SOCK_STREAM)
self.skt.connect((self.IP, self.port))
self.skt.setblocking(0)
def listen(self):
BUFFER_SIZE = 1024
try:
data = self.skt.recv(BUFFER_SIZE)
except SocketError:
pass
else:
if not data:
return
for line in data.split('\n'):
if self.receive(line):
return True
示例9: AutobusConnection
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import connect [as 别名]
class AutobusConnection(AutobusConnectionSuper):
"""
A connection to an Autobus server. The typical way to use libautobus is to
create an instance of this class and go from there.
Right now, all interfaces that are to be made available must be specified
before the connection is connected for the first time. They can be
specified after, but this class won't register them until it reconnects.
If the connection to the autobus server is lost, all currently-pending
functions etc will raise an exception, and this class will attempt to
re-establish a connection and re-register interfaces.
Subscripting an instance of this class is the same as calling
get_interface(). For example, a wrapper around the interface "example" on
the server could be obtained with some_autobus_connection["example"].
Autobus provides introspection and additional information via the built-in
autobus interface. You can access it with get_interface("autobus") or
connection["autobus"]. Calling
connection["autobus"].list_functions("autobus") will list all of the
functions available on the autobus interface along with more documentation
on how to use them.
If reconnect is True (the default), the connection will reconnect itself
and re-register all of its local interfaces and functions when it gets
disconnected. It will continue attempting to reconnect indefinitely. If
reconnect is False, it's up to the on_disconnect function (or some other
functionality) to call the connect method when the connection is lost.
If print_exceptions is True, any exceptions thrown by a local function
invoked by a remote client will be printed with traceback.print_exc()
before being sent back to the client that invoked the function. This is
useful when a function is raising an unexpected error and more information
about the error, such as its traceback, is needed.
"""
def __init__(self, host=None, port=None, reconnect=True,
print_exceptions=False, on_connect=lambda: None,
on_disconnect=lambda: None):
"""
Creates a new connection. This doesn't actually connect to the
autobus server; use connect() or start_connecting() for that.
"""
if host is None:
host = os.getenv("AUTOBUS_SERVER")
if host is None:
host = "localhost"
if port is None:
port = os.getenv("AUTOBUS_PORT")
if port is None:
port = DEFAULT_PORT
if isinstance(port, basestring):
port = int(port)
self.socket = None
self.host = host
self.port = port
self.reconnect = reconnect
self.on_connect = on_connect
self.on_disconnect = on_disconnect
self.print_exceptions = print_exceptions
self.on_connect_lock = RLock()
self.interfaces = {} # Map of names to LocalInterface objects
# representing interfaces we've registered
self.is_shut_down = False
self.send_queue = Queue()
self.receive_queues = {} # Maps message ids expecting responses to the
# corresponding queues waiting for the message response
self.event_listeners = {} # Maps tuples containing an interface name
# and an event name to a list of functions listening for the specified
# event to fire on the server. At least one entry must be present in
# each list in order for AutobusConnection to auto-register a
# listener on the specified event on connect, even if it's as simple
# as lambda: None.
self.object_values = {} # Maps tuples containing an interface name and
# an object name to the object's current value as sent by the server.
# This dict gets replaced every time we disconnect.
self.object_listeners = {} # Maps tuples containing an interface name
# and an object name to a list of functions listening for changes in
# that object. At least one entry must be present in each list in order
# for AutobusConnection to auto-register a watch on the object on
# connect, even if it's as simple as lambda: None.
def shutdown(self):
self.is_shut_down = True
try:
self.socket.shutdown(SHUT_RDWR)
except:
pass
try:
self.socket.close()
except:
pass
def add_interface(self, name, interface=None):
"""
Adds an interface that will be automatically registered with the server
on connecting. All methods that do not start with an underscore on the
specified object will be registered on the interface as functions. The
specified object's docstring, if it has one, will be used as the
interface's documentation.
#.........这里部分代码省略.........