如何启动服务器到客户端的套接字连接?

时间:2020-02-11 11:03:39

标签: python-3.x sockets

我已经在客户端和服务器之间设置了一个tcp套接字,非常基本。客户端:

#!/usr/bin/env python3

import socket

# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# get local machine name
host = "81.88.95.250"                      

port = 25000

# connection to hostname on the port.
s.connect((host, port))                               

# Receive no more than 1024 bytes
msg = s.recv(1024)                                     

s.close()
print (msg.decode('ascii'))

服务器端:

#!/usr/bin/env python3
import socket                                         

# create a socket object
serversocket = socket.socket(
                socket.AF_INET, socket.SOCK_STREAM) 

# get local machine name
host = socket.gethostname()                           

port = 25000                                           

# bind to the port
serversocket.bind((host, port))                                  

# queue up to 5 requests
serversocket.listen(5)                                           

while True:
   # establish a connection
   clientsocket,addr = serversocket.accept()      

   print("Got a connection from %s" % str(addr))

   msg = 'Thank you for connecting'+ "\r\n"
   clientsocket.send(msg.encode('ascii'))
   clientsocket.close()

我的目标是从客户端向服务器发送通知,这很容易。困难的部分是,在某些情况下,我还需要从服务器启动连接并向客户端发送命令,并且必须在收到命令后立即执行该命令,因此我无法设置定期的“轮询”。但是我对此感到很困惑,因为客户端位于NAT后面,没有公开IP。

0 个答案:

没有答案