我是新來接,請原諒我完全不理解。爲什麼我在Python中出現錯誤「連接被拒絕」? (插座)
我有一個服務器腳本(server.py):
#!/usr/bin/python
import socket #import the socket module
s = socket.socket() #Create a socket object
host = socket.gethostname() #Get the local machine name
port = 12397 # Reserve a port for your service
s.bind((host,port)) #Bind to the port
s.listen(5) #Wait for the client connection
while True:
c,addr = s.accept() #Establish a connection with the client
print "Got connection from", addr
c.send("Thank you for connecting!")
c.close()
和客戶端腳本(client.py):
#!/usr/bin/python
import socket #import socket module
s = socket.socket() #create a socket object
host = '192.168.1.94' #Host i.p
port = 12397 #Reserve a port for your service
s.connect((host,port))
print s.recv(1024)
s.close
我去我的桌面終端,並通過鍵入啓動腳本:
python server.py
之後,我去我的筆記本電腦終端,並啓動客戶端腳本:
python client.py
,但我得到了以下錯誤:
File "client.py", line 9, in
s.connect((host,port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
我一直在使用不同的端口號無濟於事嘗試。但是,我可以在客戶端腳本中使用相同的ip和gethostname()方法獲取主機名,並且可以ping桌面(服務器)。
嘗試使用[遠程登錄(http://en.wikipedia.org/wiki/遠程登錄)。它經常幫助我。輸入您的終端telnet [IP] 12397'(用'gethostname()'返回的內容替換IP)。如果你這樣做,你應該看到'謝謝你連接'。如果沒有,請告訴我什麼telnet返回。 – Matt3o12 2013-04-21 11:56:32
'telnet'適用於我,但是我發送的每個命令都會創建一個'HTTP/1.1 400 Bad Request'並關閉連接。 – 2015-03-20 17:21:46