我一直在嘗試設置套接字,這些套接字將通過互聯網工作。我通過堆棧溢出來搜索高位和低位,似乎無法找到我需要的答案。Python 3在互聯網上使用套接字
當我運行server.py我收到此錯誤:
Traceback (most recent call last):
File "server.py", line 16, in <module>
serversocket.bind((host, port))
OSError: [WinError 10049] The requested address is not valid in its context
請注意,下面好像在本地的無線網絡的工作。
服務器代碼:
# server.py
import socket
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
#get ip address
print("You are the server.")
print("What is your ip? If you do not know, look up <my ip> on google.")
host = input(">")
port = 0
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
clientsocket,addr = serversocket.accept()
def messenger():
# establish a connection
tm = clientsocket.recv(1024)
tm = tm.decode('ascii')
if tm == "9+10":
message = "21"
elif tm == "sweg":
message = "swegedy swooty feel the booty"
else:
message = "feggeet"
clientsocket.send(message.encode('ascii'))
messenger()
messenger()
的客戶端代碼:
# client.py
import socket
#get ip address
print("You are the client.")
print("What is your servers ip?")
host = input(">")
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 0
s.connect((host, port))
# Receive no more than 1024 bytes
def messenger():
message = input("command:")
s.send(message.encode("ascii"))
tm = s.recv(1024)
print(tm.decode('ascii'))
messenger()
messenger()
據我瞭解,這應該工作,只要我插入一個公網IP地址。但是,我只是得到了這個錯誤信息。
我在做什麼錯?
請注意,你的'messenger'函數最終會溢出堆棧,因爲你一遍又一遍地從本身調用它。相反,只要將讀/寫邏輯放入一個循環中並在接收到某個特定的字符串時退出循環(以及信使功能)。 – KevinDTimm
好的,我會解決這個問題。謝謝。 –