python socket編程騰訊雲下報錯[Errno 99] Cannot assign requested address的解決方式


先寫服務端server.py:

import socket
import time
 
HOST = '172.17.xx.xx'  #服務器的私網IP
#HOST = 'localhost'
PORT = 8001
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
sock.bind((HOST, PORT))  
sock.listen(5)  
while True:  
    connection,address = sock.accept()  
    try:  
        connection.settimeout(10)  
        buf = connection.recv(1024)  
        if buf:  
            connection.send(b'welcome to server!')
            print('Connection success!')
        else:  
            connection.send(b'please go out!')  
    except socket.timeout:  
        print ('time out')
    connection.close()  
 

客戶端client.py:

import socket
import time
 
#HOST = 'localhost' 
HOST = '212.64.xx.xx'  #服務器的公網IP
PORT = 8001
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
sock.connect((HOST, PORT))  
time.sleep(2)  
sock.send(b'1')
print (sock.recv(1024).decode())
sock.close()  

使用本地測試(即HOST='localhost')是可以的,但是在騰訊雲/阿里雲上報錯“[Errno 99] Cannot assign requested address”,解決方法:服務端的ip填私網ip,客戶端填公網ip。

 

 

參考鏈接:

1. https://blog.csdn.net/weixin_41656968/article/details/80042554

2. https://blog.csdn.net/weixin_43146445/article/details/93506761


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM