Python套接字:错误接收数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python套接字:错误接收数据相关的知识,希望对你有一定的参考价值。

我写了一个网络应用程序。服务器能够在给定的子网上查找客户端。如果客户端从服务器接收验证消息,它将响应服务器。一切都很好,但服务器,它不能从客户接收。

客户:

def ListenServer():
    # Listen init signal from Server to send data

    HOST = ''                 # Symbolic name meaning all available interfaces
    PORT = 50007              # Arbitrary non-privileged port

    # UDP Socket
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((HOST, PORT))
    data, addr = s.recvfrom(1024)
    if data == 'Authen':
        SocketConnect(addr[0])

def SocketConnect(HOST):
    # Connect to Server to send data
    print HOST
    PORT = 50008              # The same port as used by the server

    # Create Socket
    print "Create Socket"
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket.error, e:
        print "Error creating socket: %s" %e
        sys.exit(1)

    # Connect
    print "Connect"
    try:
        s.connect((HOST, PORT))
    except socket.error, e:
        print "Connection error: %s" %e
        sys.exit(1)

    # Send Data
    print "Send Data"
    try:
        s.sendall('Hello, world')
    except socket.error, e:
        print "Error sending data: %s" % e
        sys.exit(1)


    # Close Socket
    s.close()
    print "Close Socket"

ListenServer()

服务器:

from netaddr import IPAddress
import socket
import sys
import ipaddress
import time


def FindAgent():
    PORT = 50007          # Port use to find Agent

    #Find broadcast address

    """IPAddress("255.255.255.0").netmask_bits()        #Convert Subnet Mask to Prefix Length, Result is 24"""
    try :
        HOST = str(ipaddress.ip_network(u'192.168.10.0/24')[-1])
    except ValueError as e :
        """e = sys.exc_info()[0]  # Find Exception you need"""
        print e

    # UDP client
    MESSAGE = "Authen"
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    for x in range(0,2):
        sock.sendto(MESSAGE, (HOST, PORT))


def ListenClient():
    # Listen Client sent data
    HOST = socket.gethostbyname(socket.gethostname())
    PORT = 50008
    # TCP socket

    # Create Socket
    print "Create Socket"
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket.error, e:
        print "Error creating socket: %s" %e
        sys.exit(1)

    # Bind
    print "Bind"
    try:
        s.bind((HOST, PORT))
    except socket.error, e:
        print "Error bind: %s" %e
        sys.exit(1)

    # Listen
    print "Listen"
    try:
        s.listen(10)
    except socket.error, e:
        print "Error listen: %s" %e
        sys.exit(1)

    # Accept data from client
    print "Accept data from client"
    try:
        conn, addr = s.accept()
        data = s.recv(1024)
    except socket.error, e:
        print "Error listen: %s" %e
        sys.exit(1)

    print data
    s.close()

FindAgent()
ListenClient()

服务器出错:

Create Socket
Bind
Listen
Accept data from client
Error listen: [Errno 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
[Finished in 0.8s with exit code 1]
[shell_cmd: python -u "C:UsersWin7_LabDesktopServer.py"]
[dir: C:UsersWin7_LabDesktop]
[path: C:Python27;C:Python27Scripts;C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:WindowsSystem32WindowsPowerShellv1.0]

没有服务器上的行data = s.recv(1024),它工作正常。但有了它,错误就出现了。任何人都可以告诉我为什么会这样吗?

答案

崩溃来自s.recv(1024),因为你说这是因为你的服务器上的接收(.recv())方法需要在客户端连接上调用。

请遵循以下示例:here

服务器文件:

conn, addr = s.accept()
data = conn.recv(1024)

客户档案:

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((HOST, PORT))
data = s.recv(1024)

如您所见,客户端从套接字(服务器)接收数据。服务器从客户端连接接收数据。

希望这很有用。

编辑添加一些示例链接。

您可以在这些教程中找到所需内容:

以上是关于Python套接字:错误接收数据的主要内容,如果未能解决你的问题,请参考以下文章

Python套接字不接收而不发送

用于接收数据的套接字的Tkinter线程

python套接字接收二进制数据

Python 3套接字客户端发送数据和C++套接字服务器接收偏移数据?

确保通过 Python 中的 UDP 套接字接收所有数据

如何使用 Python 从 Web 套接字接收数据