【发布时间】:2017-12-10 21:23:02
【问题描述】:
我最近开始学习使用 python 进行套接字编程。从最基本的服务器端和客户端在同一台电脑上的脚本开始,我写了如下代码。
服务器.py
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()
客户端.py
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
【问题讨论】:
标签: python