0
import socket

MAX_BUFFER_SIZE = 4096

class ClientSocket:

    def __init__(self):
        print("Client socket started....")
        self.soc = None

    def send_to_Server(self, data):
        print('Time to send data to Server..... %s', data)
        self.soc.send(data.encode("utf8"))   

    def receive_from_Server(self):
        print('Time to receive from Server.....')
        result_bytes = self.soc.recv(MAX_BUFFER_SIZE)
        result_string = result_bytes.decode("utf8")
        print("Result from server is {}".format(result_string))

    def start_client(self):
        self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.soc.connect(("localhost", 8000))
        print('Client connected....')

husainshoab@hs-Len:~$ python IOTDeviceSocket.py

Traceback (most recent call last): File "IOTDeviceSocket.py", line 7, in class ClientSocket: File "IOTDeviceSocket.py", line 11, in ClientSocket self.soc = None NameError: name 'self' is not defined

2
  • 1
    Can you show us how you instantiate this class ? Do you have a line like client_socket = ClientSocket() Commented Mar 28, 2018 at 6:48
  • Can you fix the indentation in your question and show how you run this code? Commented Mar 28, 2018 at 6:54

2 Answers 2

2

There appears to be nothing wrong with your code. I just used it to create a simple test application

# ClientSocket.py
import socket

MAX_BUFFER_SIZE = 4096

class ClientSocket:

    def __init__(self):
        print("Client socket started....")
        self.soc = None

    def send_to_Server(self, data):
        print('Time to send data to Server..... %s', data)
        self.soc.send(data.encode("utf8"))   

    def receive_from_Server(self):
        print('Time to receive from Server.....')
        result_bytes = self.soc.recv(MAX_BUFFER_SIZE)
        result_string = result_bytes.decode("utf8")
        print("Result from server is {}".format(result_string))

    def start_client(self):
        self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.soc.connect(("localhost", 8000))
        print('Client connected....')


cs = ClientSocket()

cs.start_client()
cs.send_to_Server('Hello')
cs.receive_from_Server()

here's a simple test server which just spits back some JSON data

# test_server.py
import socket
from datetime import datetime
import json

def logMessage(clientMessage):
    logTime = datetime.today();
    msg = "{} | {}\n".format(logTime, clientMessage)
    print msg


TCP_PORT = 8000

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', TCP_PORT))

# listen() puts the socket into server mode, 
server.listen(1)
while True:
    # wait for an incoming connection
    connection, address = server.accept()

    try:
        # receive data in chunks of 64 bytes
        while True:
            data = connection.recv(64)

            # how do we know if we received all the data?

            if data:
                # we received data from the client, log it to the file
                logMessage(data)

                response = {
                    'name'       : 'Jonathan Swift',
                    'occupation' : 'author' 
                }

                jsonResponse  = json.dumps(response)
                messageLength = len(jsonResponse)
                bytesSent     = 0

                # send a response to the client after turning our dict into
                # a JSON string
                while(bytesSent < messageLength):
                    sent = connection.send(jsonResponse)
                    bytesSent += sent
            else:
                # no data, break out of receiving loop
                break
    except Exception as e:
        raise
    finally:

        connection.close()
Sign up to request clarification or add additional context in comments.

5 Comments

The spacing is a formatting issue of the question, not the original problem. If the script was spaced exactly as in the question it would throw an IndentationError as there is an indented block expected after the class definition
Hmm. Well, that is valid Python code. He's defined a class that's empty. self wouldn't be defined in the methods thus the issue, "self is not defined"
a) it is not valid code there must be at least a pass in the class body. b) even if it was valid, then self would be the first argument of the function and would therefore be defined
ah, yeah, you're right. There does have to be a pass in the body of the class.
Great effort. I am suspecting that there is something wrong in how OP is executing his code
-1
import socket

MAX_BUFFER_SIZE = 4096

class ClientSocket:
    soc = None
    def __init__(self):
        print("Client socket started....")
        self.soc = None

    def send_to_Server(self, data):
        print('Time to send data to Server..... %s', data)
        self.soc.send(data.encode("utf8"))

    def receive_from_Server(self):
        print('Time to receive from Server.....')
        result_bytes = self.soc.recv(MAX_BUFFER_SIZE)
        result_string = result_bytes.decode("utf8")
        print("Result from server is {}".format(result_string))

    def start_client(self):
        self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.soc.connect(("localhost", 8000))
        print('Client connected....')

you should define the soc variable after class statement so that you can use it globally.

5 Comments

That is not how classes work in python. You don't need to declare class variables in that way. Also the problem has to do with self, not with soc
He is accessing soc variable just like this self.soc in every class,so python may find the global variable soc of class ClientSocket which is not defined...
I am guessing you are not really familiar with OOP in python. Jsut give it a try, it works just fine this way. You don't need to explicitly define class variables, you just asign values to self.<variable name>. Also: The error reported by OP is not soc is not defined, but self is not defined
@SR_Mehta: self.soc is defined on __init__(), so it is not a problem.
@GiacomoCatenazzi you don't even need to define them in __init__(), you can also do it in other class methods (although that could be considered bad style)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.