无法通过套接字与Python连接

时间:2017-07-28 13:13:41

标签: python sockets

问题如下。

我有以下服务器:

import socket


class Receiver:

    TCP_IP = '127.0.0.1'
    TCP_PORT = 2999
    BUFFER_SIZE = 20

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((TCP_IP, TCP_PORT))
    s.listen(1)

    conn, addr = s.accept()
    print('Connection address:', addr)
    while 1:
        data = conn.recv(BUFFER_SIZE)
        if not data: break
        print("received data:", data)
        conn.send('0x55'.encode())  # echo
    conn.close()

客户:

import socket import logging

class NvgClient:
    _instance = None
    def __init__(self):
        self.s = socket.socket()
        self.s.settimeout(3)
        self.connect()
        return

    def __del__(self):
        try:
            self.s.close()
        finally:
            return

    @staticmethod
    def getInstance():
        if(NvgClient._instance == None):
            NvgClient._instance = NvgClient()
        return NvgClient._instance

    def connect(self):
        try:
            print("****** TRYING_TO_CONNECT_TO_SOCKET ********")
            self.s.connect(('127.0.0.0', 2999))
        except socket.error:
            self.s.close()
            self.s = socket.socket()
            self.s.settimeout(3)
            self.connect()
            logging.error("Socket can`t connect! Reconnected.")
        return

    def send(self, data: bytearray):
        try:
            print("****** TRYING_TO_SEND_DATA ********")
            self.s.send(data)
            logging.info(str(data))
            rdata = self.s.recv(1024)
            if(rdata[0] == 0x55 and rdata[1:5] == data[0:4]):
                logging.info('NVG OK')
                return True
            else:
                logging.info('NVG BAD')
        except socket.timeout:
            self.s.close()
            self.connect()
        except IndexError:
            logging.info('Server returns nothing. Reconnecting.')
            self.s.close()
            self.s = socket.socket()
            self.s.settimeout(3)
            self.connect()
            return False

但是当我尝试发送一些数据时,无法连接到服务器: self.s.connect((' 127.0.0.0',2999))。我得到了socket.error。

代码中是否有任何错误或错误?对于其他简单示例或telnet,服务器运行良好。

1 个答案:

答案 0 :(得分:1)

您需要连接到localhost,即:

127.0.0.1

而不是

127.0.0.0

正如您为客户写的那样(虽然服务器还可以)