[英]Python Socket Programming - Server Client basic
我最近開始學習使用python進行套接字編程。 從同一台計算機上服務器和客戶端的最基本腳本開始,我編寫了以下代碼。
import socket
import time
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
serversocket.bind((host,port))
serversocket.listen(5)
while True:
clientsocket, addr = serversocket.accept()
print("Got a connection from %s" %str(addr))
currentTime = time.ctime(time.time()) + "\r\n"
clientsocket.send(currentTime.encode('ascii'))
clientsocket.close()
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
s.connect((host,port))
tm = s.recv(1024)
s.close()
print("The time got from the server is %s" %tm.decode('ascii'))
我正在使用spyder IDE。 每當我在IPython控制台中運行客戶端時,都會得到以下信息:“ ConnectionRefusedError:[WinError 10061]無法建立連接,因為目標計算機主動拒絕了它。”
每當我運行服務器時,我都會得到一個永無止境的過程。
那么,我應該怎么做才能使這項工作呢?
感謝您的任何幫助!
積分:-http: //www.bogotobogo.com/python/python_network_programming_server_client.php
嘗試將socket.gethostname()
更改為socket.gethostbyname(socket.gethostname())
。 gethostbyname
返回主機名的IP。 您要設置一個套接字以連接到IP端口。 或者,由於您在本地運行所有內容,因此只需將客戶端/服務器的host
直接設置為"127.0.0.1"
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.