【问题标题】:Python Socket Programming - Server Client basicPython Socket 编程 - 服务器客户端基础
【发布时间】: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

【问题讨论】:

  • 谷歌搜索“ConnectionRefusedError: [WinError 10061]”给了我thisthis,还有其他一些。你看过那些吗?

标签: python


【解决方案1】:

尝试将socket.gethostname() 更改为socket.gethostbyname(socket.gethostname())gethostbyname 返回主机名的 ip。您想设置一个套接字以连接到一个 ip、端口。或者,由于您在本地运行所有内容,只需将您的 host 设置为 "127.0.0.1" 直接用于客户端/服务器。

【讨论】:

  • 我可能只是建议使用'localhost','127.0.0.1', or '0.0.0.0' ...但很好的答案+1
猜你喜欢
  • 1970-01-01
  • 2014-10-19
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多