【发布时间】:2021-02-02 07:27:11
【问题描述】:
我一直在尝试学习python中套接字编程的基础知识。我已经尝试了代码,客户端连接似乎不起作用。
server.py的代码
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.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 'Got connection from', addr
c.send('Thank you for connecting')
c.close()
client.py的代码
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close()
当我同时运行客户端和服务器文件时,我收到错误 s.connect((host, port)) ConnectionRefusedError: [Errno 111] Connection refused。
当我运行服务器文件时,与端口 12345 的连接处于活动状态,但客户端文件未连接到它。我已尝试根据在线建议修改代码,但仍然没有运气。任何有助于完成这项工作的方法是真的很感激..提前谢谢你。
P:S 我在本地机器上运行它
【问题讨论】:
-
我试过了,但仍然收到错误
-
你有一个缩进错误。