基本 Python 客户端套接字示例 [英] Basic Python client socket example

查看:42
本文介绍了基本 Python 客户端套接字示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图了解套接字的工作原理,并且我一直在尝试挑选一些我在 这个页面 一个非常简单的客户端套接字程序.由于这是基本示例代码,我假设它没有错误,但是当我尝试编译它时,我收到以下错误消息.

I've been trying to wrap my head around how sockets work, and I've been trying to pick apart some sample code I found at this page for a very simple client socket program. Since this is basic sample code, I assumed it had no errors, but when I try to compile it, I get the following error message.

文件client.py",第 4 行,在client_socket.connect(('localhost', 5000))文件",第 1 行,在连接中socket.error: [Errno 111] 连接被拒绝

File "client.py", line 4, in client_socket.connect(('localhost', 5000)) File "", line 1, in connect socket.error: [Errno 111] Connection refused

我几乎在谷歌上搜索了这个错误的每个部分,遇到类似问题的人似乎已经通过更改端口号、使用连接"而不是绑定"以及其他一些东西得到了帮助,但没有一个适用于我的情况.非常感谢任何帮助,因为我对网络编程很陌生,对 python 也很陌生.

I've googled pretty much every part of this error, and people who've had similar problems seem to have been helped by changing the port number, using 'connect' instead of 'bind,' and a few other things, but none of them applied to my situation. Any help is greatly appreciated, since I'm very new to network programming and fairly new to python.

顺便说一下,这里是代码,以防链接因任何原因不起作用.

By the way, here is the code in case that link doesn't work for whatever reason.

#client example
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 5000))
while 1:
    data = client_socket.recv(512)
    if ( data == 'q' or data == 'Q'):
        client_socket.close()
        break;
    else:
        print "RECIEVED:" , data
        data = raw_input ( "SEND( TYPE q or Q to Quit):" )
        if (data <> 'Q' and data <> 'q'):
            client_socket.send(data)
        else:
            client_socket.send(data)
            client_socket.close()
            break;

推荐答案

它正在尝试连接到在端口 5000 上运行的计算机,但连接被拒绝.你确定你有一台服务器在运行吗?

It's trying to connect to the computer it's running on on port 5000, but the connection is being refused. Are you sure you have a server running?

如果没有,您可以使用 netcat 进行测试:

If not, you can use netcat for testing:

nc -l -k -p 5000

某些实现可能要求您省略 -p 标志.

Some implementations may require you to omit the -p flag.

这篇关于基本 Python 客户端套接字示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆