本文整理汇总了Python中socket.connect函数的典型用法代码示例。如果您正苦于以下问题:Python connect函数的具体用法?Python connect怎么用?Python connect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了connect函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: main
def main():
host = ''
port = 80
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
socket.connect(host, port)
except Exception as e:
print ("Couldn't acquire port :", port,"\n")
try:
port = 8080
socket.connect(host, port)
except Exception as e:
print ("Couldn't connect to port 80 ad 8080")
print ("Success: client connected to host: ", host, "and port: ", port)
while True:
sys.stdout.write("Client ready to send request:")
cmd = str(sys.argv)
print ("Sending command to server: %s" % cmd)
print ("Host name: %s" % str(sys.argv[1]))
print ("Port: %s" % str(sys.argv[2]))
print ("Filename: %s" % str(sys.argv[2]))
socket.send(cmd)
response = socket.recv(1024)
if response:
sys.stdout.write(response)
socket.close()
开发者ID:jdaniels539,项目名称:Python-HTTP-Server,代码行数:35,代码来源:WebClient.py
示例2: send
def send(self, service_name, method, *args):
socket = NetRPC()
socket.connect(self.hostname, self.port)
socket.mysend((service_name, method, )+args)
result = socket.myreceive()
socket.disconnect()
return result
开发者ID:diogocduarte,项目名称:flask-openerp,代码行数:7,代码来源:rpc.py
示例3: send
def send(self, message_type=None, message_type_args={}, request_id=None):
if(not request_id):
request_id = uuid.uuid4()
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://{0}:{1}".format(self._ip, self._port))
socket.poll(timeout=1)
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
lib.debug.info("Sending request {0} …".format(request_id))
timestarted = time.time()
hostdetails = simplejson.dumps({'hostname':lib.hostname_ip.hostname, 'ip':lib.hostname_ip.ip})
send_msg = simplejson.dumps(self.process(message_type, message_type_args,hostdetails))
socket.send_multipart([bytes(unicode(request_id)), bytes(unicode(hostdetails)), bytes(unicode(message_type)), bytes(unicode(send_msg))])
while(True):
sockets = dict(poller.poll(10000))
if(sockets):
for s in sockets.keys():
if(sockets[s] == zmq.POLLIN):
try:
(recv_id, recv_hostdetails, recv_msg_type, recved_msg) = s.recv_multipart()
recv_message = self.process(recv_msg_type, recved_msg,recv_hostdetails)
lib.debug.info("Received reply %s : %s [ %s ]" % (recv_id, recv_message, time.time() - timestarted))
except:
lib.debug.info (sys.exc_info())
break
break
lib.debug.info ("Reciever Timeout error : Check if the server is running")
socket.close()
context.term()
开发者ID:shrinidhi666,项目名称:dev_ops,代码行数:34,代码来源:transport.py
示例4: orca_producer
def orca_producer(host, port=44666):
"""
Pushes CMOS and base current records to a ZMQ Push/Pull socket
to be parsed by other workers. CMOS rates and base currents are
pushed to ports 5557 and 5558 respectively.
See `zeromq.org <http://zeromq.org>`_ for more information.
"""
socket = Socket()
socket.connect(host, port)
cmos_context = zmq.Context()
cmos = cmos_context.socket(zmq.PUSH)
cmos.bind('tcp://127.0.0.1:5557')
base_context = zmq.Context()
base = base_context.socket(zmq.PUSH)
base.bind('tcp://127.0.0.1:5558')
while True:
id, rec = socket.recv_record()
if id == CMOS_ID:
cmos.send_pyobj((id,rec))
if id == BASE_ID:
base.send_pyobj((id,rec))
开发者ID:fbdescamps,项目名称:minard,代码行数:25,代码来源:orca.py
示例5: get_replay
def get_replay(name, query, config, context=None):
endpoint = config.get('replay_endpoints', {}).get(name, None)
if not endpoint:
raise IOError("No appropriate replay endpoint "
"found for {0}".format(name))
if not context:
context = zmq.Context(config['io_threads'])
# A replay endpoint isn't PUB/SUB but REQ/REP, as it allows
# for bidirectional communication
socket = context.socket(zmq.REQ)
try:
socket.connect(endpoint)
except zmq.ZMQError as e:
raise IOError("Error when connecting to the "
"replay endpoint: '{0}'".format(str(e)))
# REQ/REP dance
socket.send(fedmsg.encoding.dumps(query))
msgs = socket.recv_multipart()
socket.close()
for m in msgs:
try:
yield fedmsg.encoding.loads(m)
except ValueError:
# We assume that if it isn't JSON then it's an error message
raise ValueError(m)
开发者ID:axilleas,项目名称:fedmsg,代码行数:29,代码来源:__init__.py
示例6: _socketRequest
def _socketRequest(self, scheme, host, port, payload):
socket = self._getSocketForScheme(scheme)
socket.connect((host, port))
socket.sendall(payload)
data = socket.recv(1024)
socket.close()
return data
开发者ID:buglloc,项目名称:pocs,代码行数:7,代码来源:file_uploader.py
示例7: main
def main(network, nick, chan, port):
socket.connect((network, port))
irc = ssl.wrap_socket(socket)
irc.send(bytes("NICK %s\r\n" % nick, "UTF-8"))
print(irc.recv(4096))
irc.send(bytes("USER %s %s %s :My bot\r\n" % (nick, nick, nick), "UTF-8"))
print(irc.recv(4096))
irc.send(bytes("JOIN #%s\r\n" % chan, "UTF-8"))
print(irc.recv(4096))
while True:
data = irc.recv(4096)
print(data)
user_in = input(":")
if user_in.find("!s") != -1:
user_in = user_in[3:]
searchterm = user_in
try:
print_search(searchterm)
except KeyError:
print("No Result Found")
print(user_in)
data = data.decode("UTF-8")
if data.find("PING") != -1:
irc.send(bytes("PONG " + data.split()[1] + "\r\n", "UTF-8"))
if user_in.find("!q") != -1:
irc.send(bytes("QUIT\r\n", "UTF-8"))
exit()
if user_in.find("!d") != -1: ##to check for xfer
bot_name = "Dragonkeeper"
pack_number = "1"
# user_in = user_in[3:] ## for option select !d 1 will show as 1
irc.send(bytes("PRIVMSG " + bot_name + " :xdcc send " + pack_number + "\r\n", "UTF-8"))
开发者ID:TheDragonkeeper,项目名称:pyixirc,代码行数:33,代码来源:ixirc.py
示例8: localization_client
def localization_client(ip,port):
context = zmq.Context()
# Socket to talk to server
print "Connecting to localization server ... "
socket = context.socket(zmq.REQ)
socket.connect(("tcp://localhost:%d" % port))
# Do 10 requests, waiting each time for a response
while True:
# print("Sending request %s ... " % request)
socket.send(b"pose")
# Get the reply.
result = json.loads(socket.recv(1024));
# printing the result
# print(result)
# In order to access position : (result["pos"]["x"],result["pos"]["y"],result["pos"]["z"])
# In order to access orientation : (result["orient"]["w"],result["orient"]["x"],result["orient"]["y"],result["orient"]["z"])
print "Position : " , (float(result["pos"]["x"]),float(result["pos"]["y"]),float(result["pos"]["z"]))
print "Orientation : " , (float(result["orient"]["w"]),float(result["orient"]["x"]),float(result["orient"]["y"]),float(result["orient"]["z"]))
# wait for a while
time.sleep(0.050)
开发者ID:Cdfghglz,项目名称:indriya,代码行数:25,代码来源:experimot_zmq_client.py
示例9: getFile
def getFile(filename):
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:1337")
socket.send(filename)
response = socket.recv_json()
return response
开发者ID:EkaterinaZakharova,项目名称:ZeroMQ,代码行数:7,代码来源:master.py
示例10: _worker
def _worker(self,worker_url, worker_id=uuid.uuid4()):
if (sys.platform.lower().find("linux") >= 0):
setproctitle.setproctitle("server-worker")
lib.debug.info (worker_url)
context = zmq.Context()
# Socket to talk to dispatcher
socket = context.socket(zmq.REP)
socket.poll(timeout=1)
socket.connect(worker_url)
while True:
(request_id_rep, state_name_rep, topic_rep, msg_rep) = socket.recv_multipart()
rep_sock.send_multipart([request_id_rep, state_name, msg_rep])
lib.debug.debug(msg_rep)
try:
msg_reved = simplejson.loads(msg_rep)
if (msg_reved['status'] == "free"):
hosts_recieved[msg_reved['hostid']] = msg_reved
lib.debug.debug("sending state : " + state_name_rep + " : ")
else:
return (msg_reved['status'] + " : " + msg_reved['request_id'])
except:
lib.debug.error(str(state_name) + " : " + str(request_id) + " : " + str(sys.exc_info()))
return (str(state_name) + " : " + str(request_id) + " : " + str(sys.exc_info()))
while True:
received = socket.recv_multipart()
lib.debug.info("Received request: [ {0} ] -> [ {1} ]".format(str(worker_id),msg_type_args))
reply = self.process(received)
reply_to_send = simplejson.dumps(reply)
socket.send_multipart([bytes(unicode(hostid)),bytes(unicode(request_id)),bytes(unicode(reply_to_send))])
lib.debug.info("Replied to request: [ {0} ] -> [ {1} ]".format(str(worker_id), msg_type_args))
开发者ID:shrinidhi666,项目名称:dev_ops,代码行数:32,代码来源:transport.py
示例11: InitResource
def InitResource(version):
global database, resource, socket, listflie, tfidfmodel, tfidfdict, table_state_strategy
if version is 'v1':
listfile = 'cnn_qa_human_response_name.list'
if version is 'v2':
listfile = 'cnn_qa_human_response_name_high_app.list'
if version is 'v2.5':
listfile = 'cnn_qa_human_response_name_high_app.list'
tfidfdict = corpora.Dictionary.load(tfidfname + '.dict')
tfidfmodel = models.tfidfmodel.TfidfModel.load(tfidfname + '.tfidf')
if version is 'v3':
listfile = 'cnn_hr_v1_v2.list'
tfidfdict = corpora.Dictionary.load(tfidfname + '.dict')
tfidfmodel = models.tfidfmodel.TfidfModel.load(tfidfname + '.tfidf')
if version is 'v4':
listfile = 'cnn_hr_v1_v2_v4.list'
tfidfdict = corpora.Dictionary.load(tfidfname + '.dict')
tfidfmodel = models.tfidfmodel.TfidfModel.load(tfidfname + '.tfidf')
datalist=[line.strip() for line in open(listfile)]
database = Loader.LoadDataPair(datalist)
resource = Loader.LoadLanguageResource()
global TemplateLib, TopicLib, TreeState, Template,model
TemplateLib = Loader.LoadTemplate(template_list)
TopicLib = Loader.LoadTopic(topicfile)
TreeState, Template = Control.Init()
model = models.Doc2Vec.load('/tmp/word2vec_50')
if wizard is 2:
context= zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")
with open('table_state_strategy.pkl') as f:
table_state_strategy = pickle.load(f)
开发者ID:echoyuzhou,项目名称:ticktock_text_api,代码行数:33,代码来源:galbackend_online_back.py
示例12: myConnect
def myConnect(socket,host,port):
while True: ## send message to log
try:
socket.connect(host,port)
break
except:
continue
开发者ID:jadams760,项目名称:CS171_HW3,代码行数:7,代码来源:HW3_Client_1.py
示例13: obtainTaskSpecFromServer
def obtainTaskSpecFromServer(ServerIP, ServerPort, TeamName):
# context = zmq.Context()
# connection_address = "tcp://" + ServerIP + ":" + ServerPort
# print "Start connection to " + connection_address
# # Socket to talk to server
# print "Connecting to server..."
# socket = context.socket(zmq.REQ)
# socket.connect(connection_address)
#
# print "Sending request ..."
# socket.send(TeamName)
#
# # Get the reply.
# message = socket.recv()
# socket.send("ACK")
# socket.close()
# print "Received message: ", message
# return message
while True:
try:
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((ServerIP, ServerPort))
errorPrinted = False
except socket.error, err:
if not errorPrinted:
rospy.loginfo("Connection to %s:%s not succsesfull: %s", ServerIP, ServerPort, err)
rospy.loginfo("retrying ...")
errorPrinted = True
rospy.sleep(1.)
else:
socket.send(MESSAGE)
return waitForData(socket)
rospy.loginfo("Connected to %s : %s", ServerIP, ServerPort)
开发者ID:ChefOtter,项目名称:smartlabatwork-release,代码行数:33,代码来源:refereeBoxClient.py
示例14: connectTo
def connectTo(peer):
socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
socket.settimeout(10)
try:
socket.connect(peer)
except:
return False
return True
开发者ID:haomingzhang,项目名称:Simple-BitTorrent-Client,代码行数:8,代码来源:Peer.py
示例15: connect
def connect(self, socket, channel):
n = self.nickname
socket.connect((self.ip, self.port))
self.socket_send(socket, "USER "+n+" "+n+" "+n+" :Jestem bogiem irc")
self.socket_send(socket, "NICK "+n)
time.sleep(10) # otherwise, it tends to not join the channel
self.functions.join_channel(self.channel)
开发者ID:asdfMaciej,项目名称:kitten-commander,代码行数:8,代码来源:main.py
示例16: connection
def connection(socket,host,port):
try:
socket.connect((host,port))
return socket
except IOError, e:
if e.errno == 101:
time.sleep(5)
connection(socket,host,port)
开发者ID:TDTR,项目名称:traffic_gen,代码行数:8,代码来源:random_communication.py
示例17: create_socket
def create_socket(socktype, endpoints,flag):
socket = zmq.Socket(zmq.Context.instance(), socktype)
socket.setsockopt(zmq.LINGER, 0)
for endpoint in endpoints:
if flag==1:
socket.bind(endpoint)
else:
socket.connect(endpoint)
return socket
开发者ID:yaobiqing0424,项目名称:pinyin4py,代码行数:9,代码来源:gsd.py
示例18: connect
def connect(self, addr):
self.connected = False
self.connecting = True
socket = self.socket
socket.setblocking(1)
socket.connect(addr)
socket.setblocking(0)
self.addr = addr
self.handle_connect_event()
开发者ID:humblec,项目名称:vdsm,代码行数:9,代码来源:betterAsyncore.py
示例19: run
def run(self):
for i in range(self.packets):
try:
bytes = random._urandom(self.size)
socket.connect(self.ip, self.port)
socket.setblocking(0)
socket.sendto(bytes,(self.ip, self.port))
except:
pass
开发者ID:theblackphone,项目名称:udp-flood,代码行数:9,代码来源:script.py
示例20: connectWithPlayer
def connectWithPlayer(clientSocket, serverSocket):
try:
socket.connect('127.0.0.1', 3000)
print('Connected with player')
return 1
except:
print('Waiting for players....')
c, addr = serverSocket.accept()
print('Connected with player')
开发者ID:achyutjoshi,项目名称:coOpPyGame,代码行数:9,代码来源:functions.py
注:本文中的socket.connect函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论