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

查看:83
本文介绍了基本的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天全站免登陆