简体   繁体   English

基本的Python客户端套接字示例

[英]Basic Python client socket example

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 在client_socket.connect((''localhost',5000))的第4行的文件“ client.py”,在connect socket.error中的第1行的文件:[Errno 111]连接被拒绝

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. 非常感谢任何帮助,因为我是网络编程的新手,而对于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;

Here is the simplest python socket example. 这是最简单的python套接字示例。

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 首先运行SocketServer.py,并确保服务器已准备好监听/接收某物。
  • Then the client send info to the server; 然后客户端将信息发送到服务器;
  • After the server received sth, it terminates 服务器收到某事后,它终止

Here is a pretty simple socket program. 这是一个非常简单的套接字程序。 This is about as simple as sockets get. 这与套接字获取一样简单。

for the client program(CPU 1) 用于客户端程序(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. 您必须用在第二台计算机网络设置中找到的IP编号替换第4行中的111.111.0.11。

For the server program(CPU 2) 对于服务器程序(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. 运行服务器程序,然后运行客户端程序。

It's trying to connect to the computer it's running on on port 5000, but the connection is being refused. 它正在尝试连接到在端口5000上运行的计算机,但是连接被拒绝。 Are you sure you have a server running? 您确定服务器正在运行吗?

If not, you can use netcat for testing: 如果没有,您可以使用netcat进行测试:

nc -l -k -p 5000

Some implementations may require you to omit the -p flag. 某些实现可能要求您省略-p标志。

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. 在运行Python代码之前。 It will act as a server listening on port 5000 for you to connect to. 它将充当服务器侦听端口5000,以供您连接。 Then you can play with typing into your Python window and seeing it appear in the other terminal and vice versa. 然后,您可以在Python窗口中键入内容,然后在其他终端中看到它,反之亦然。

You might be confusing compilation from execution. 您可能会使编译与执行混淆。 Python has no compilation step! Python没有编译步骤! :) 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. :)键入python myprogram.py ,程序立即运行,并尝试连接到开放端口5000,如果没有服务器程序在监听该端口,则会出现错误。 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. 听起来您熟悉两步语言,需要编译才能生成可执行文件-因此您将Python的运行时抱怨(“我找不到任何人在端口5000上听!”)与编译时错误相混淆。 But, in fact, your Python code is fine; 但是,实际上,您的Python代码很好; you just need to bring up a listener before running it! 您只需要在运行它之前调出一个监听器即可!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM