ILya
ILya

Reputation: 121

Can't connect through socket with Python

The issue is the following.

I have the following server:

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()

And the client:

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

But when I try to send some data, it is impossible to connect to server: self.s.connect(('127.0.0.0', 2999)). I get socket.error.

Is there any mistakes or something wrong in code? For other simple examples or telnet, server works well.

Upvotes: 0

Views: 148

Answers (1)

Coding thermodynamist
Coding thermodynamist

Reputation: 1403

You need to connect to localhost which is:

127.0.0.1

and not

127.0.0.0

as you wrote for your client (server is okay though)

Upvotes: 1

Related Questions