我想學習如何使用本教程中使用套接字:
https://www.tutorialspoint.com/python/python_networking.htm
我已經複製從網站的代碼到我的目錄,並運行它究竟正如在教程中所做的那樣,但卻遇到了錯誤。以下是教程中的代碼。錯誤:節點名稱也不servname提供,或者不知道(蟒蛇插座)
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = 'localhost' # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print("asdf")
c.send('Thank you for connecting')
c.close() # Close the connection
和client.py
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
這是我跑的控制檯命令:
python server.py &
python client.py
我運行命令後得到了這個錯誤:
Traceback (most recent call last):
File "client.py", line 9, in <module>
s.connect((host, port))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/soc ket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
在這種情況很有幫助,v我使用的python版爲是Python的2.7.10,我使用的是Mac是10.12.6
感謝版本提前
這看起來像什麼'socket.gethostname的問題()'回報。嘗試使用'host ='localhost''來代替。 –
似乎工作,我現在把其餘的代碼,看看它是否仍然有效 – fred
所以你的修復讓我過去的服務器文件的問題,但客戶端文件仍然無法工作 – fred