基本 Python 客户端套接字示例

发布于 2024-12-09 17:26:37 字数 1134 浏览 0 评论 0原文

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

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

我已经用谷歌搜索了这个错误的几乎所有部分,并且遇到类似问题的人似乎通过更改端口号、使用“连接”而不是“绑定”得到了帮助, ’以及其他一些事情,但它们都不适用于我的情况。非常感谢任何帮助,因为我对网络编程非常陌生,对 python 也相当陌生。

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

#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;

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.

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

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;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

亢潮 2024-12-16 17:26:37

这是最简单的 python 套接字示例。

服务器端:

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5) # become a server socket, maximum 5 connections

while True:
    connection, address = serversocket.accept()
    buf = connection.recv(64)
    if len(buf) > 0:
        print buf
        break

客户端:

import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
clientsocket.send('hello')
  • 首先运行SocketServer.py,并确保服务器已准备好侦听/接收某物,
  • 然后客户端向服务器发送信息;
  • 服务器收到某件事后,它终止

Here is the simplest python socket example.

Server side:

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5) # become a server socket, maximum 5 connections

while True:
    connection, address = serversocket.accept()
    buf = connection.recv(64)
    if len(buf) > 0:
        print buf
        break

Client Side:

import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
clientsocket.send('hello')
  • First run the SocketServer.py, and make sure the server is ready to listen/receive sth
  • Then the client send info to the server;
  • After the server received sth, it terminates
小镇女孩 2024-12-16 17:26:37

这是一个非常简单的套接字程序。这与套接字一样简单。

对于客户端程序(CPU 1),

import socket

s = socket.socket()
host = '111.111.0.11' # needs to be in quote
port = 1247
s.connect((host, port))
print s.recv(1024)
inpt = raw_input('type anything and click enter... ')
s.send(inpt)
print "the message has been sent"

您必须将第 4 行中的 111.111.0.11 替换为第二台计算机网络设置中找到的 IP 号。

对于服务器程序(CPU 2)

import socket

s = socket.socket()
host = socket.gethostname()
port = 1247
s.bind((host,port))
s.listen(5)
while True:
    c, addr = s.accept()
    print("Connection accepted from " + repr(addr[1]))

    c.send("Server approved connection\n")
    print repr(addr[1]) + ": " + c.recv(1026)
    c.close()

先运行服务器程序,然后运行客户端程序。

Here is a pretty simple socket program. This is about as simple as sockets get.

for the client program(CPU 1)

import socket

s = socket.socket()
host = '111.111.0.11' # needs to be in quote
port = 1247
s.connect((host, port))
print s.recv(1024)
inpt = raw_input('type anything and click enter... ')
s.send(inpt)
print "the message has been sent"

You have to replace the 111.111.0.11 in line 4 with the IP number found in the second computers network settings.

For the server program(CPU 2)

import socket

s = socket.socket()
host = socket.gethostname()
port = 1247
s.bind((host,port))
s.listen(5)
while True:
    c, addr = s.accept()
    print("Connection accepted from " + repr(addr[1]))

    c.send("Server approved connection\n")
    print repr(addr[1]) + ": " + c.recv(1026)
    c.close()

Run the server program and then the client one.

过去的过去 2024-12-16 17:26:37

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

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

nc -l -k -p 5000

某些实现可能要求您省略 <代码>-p标志。

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?

If not, you can use netcat for testing:

nc -l -k -p 5000

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

滥情空心 2024-12-16 17:26:37

您的客户端似乎正在尝试连接到不存在的服务器。在 shell 窗口中,运行:

$ nc -l 5000

在运行 Python 代码之前。它将作为服务器监听端口 5000 供您连接。然后,您可以在 Python 窗口中输入内容并看到它出现在另一个终端中,反之亦然。

It looks like your client is trying to connect to a non-existent server. In a shell window, run:

$ nc -l 5000

before running your Python code. It will act as a server listening on port 5000 for you to connect to. Then you can play with typing into your Python window and seeing it appear in the other terminal and vice versa.

财迷小姐 2024-12-16 17:26:37

您可能会混淆编译和执行。 Python没有编译步骤! :) 一旦您输入 python myprogram.py ,程序就会运行,并且在您的情况下,会尝试连接到开放端口 5000,如果没有服务器程序正在侦听,则会出现错误。听起来您熟悉两步语言,需要编译才能生成可执行文件 - 因此您对 Python 的运行时编译感到困惑,“我找不到任何人在监听端口 5000!”出现编译时错误。但事实上,你的 Python 代码没问题;你只需要在运行之前调出一个监听器即可!

You might be confusing compilation from execution. Python has no compilation step! :) As soon as you type python myprogram.py the program runs and, in your case, tries to connect to an open port 5000, giving an error if no server program is listening there. It sounds like you are familiar with two-step languages, that require compilation to produce an executable — and thus you are confusing Python's runtime compilaint that “I can't find anyone listening on port 5000!” with a compile-time error. But, in fact, your Python code is fine; you just need to bring up a listener before running it!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文