本文介绍了Python套接字:错误接收数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个网络应用程序.服务器能够根据给定的子网找到客户端.如果客户端收到来自服务器的认证消息,它将响应服务器.一切正常,但服务器无法从客户端接收.

I write a network application. The server has ability to find client base on given subnet. If the client receive authentication message from server, it will respond to server. Everything working good but server, it can't receiver from client.

客户:

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:\Users\Win7_Lab\Desktop\Server.py"]
[dir: C:\Users\Win7_Lab\Desktop]
[path: C:\Python27\;C:\Python27\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\]

没有服务器上的 data = s.recv(1024) 行,它工作正常.但是有了它,错误就会出现.谁能告诉我为什么会这样?

Without the line data = s.recv(1024) on Server, it working fine. But with it, the error show up. Can anybody please tell me why it happen ?

推荐答案

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

The crash come from s.recv(1024) as you said it's because the recieve (.recv()) methode on your server need to be called on the client connection.

按照这个例子:这里

服务器文件:

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)

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

As you see the client recieve data from socket (server).And server recieve data from client connection.

希望有用.

编辑添加一些示例链接.

您可以在这些教程中找到您想要的内容:

You can find what you want in these tutorial:

这篇关于Python套接字:错误接收数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 01:51