socket communication in python with functions

134 views
Skip to first unread message

T Obulesu

unread,
Oct 21, 2017, 6:06:47 AM10/21/17
to Python Programming for Autodesk Maya
Hi All,

I'm new to python3 and scratching my head to write a program for this logic:

classA.py
Class A:
          # class for socket communication
          basic init method that initializes port, address, connection

         method send(message):
         # for sending any message through the given port


       method receive():
       # will be keep on listening for incoming messages



classB.py

Class B:
           import the send method from class A
           send the messages from this class


classC.py

Class C:
            import the receive method from the class A
            receive all the messages from the same socket from here.



Note:
 classA.py, classB.py, ClassC.py are saved in different locations.


Can someone help me in writing the code and how can I create a single object and use it in multiple classed?

Justin Israel

unread,
Oct 21, 2017, 7:03:27 AM10/21/17
to python_in...@googlegroups.com
It might help if you explain a little more concretely about what problem you are actually trying to solve. Are you trying to create a generic socket connection class that knows how to send and receive, and then use send functionality in one subclass, and receive functionality in another? 

What code have you written thus far and where are you stuck? At this stage it seems a bit code-golfy to try and just write your specification for you. 

Are you new to python 3 and looking for a newer way to solve this problem as opposed to how you would have done it via python 2? Also... Is this homework? 

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/d457de3d-4353-47b4-906c-187d616cd9fe%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

T Obulesu

unread,
Oct 23, 2017, 8:32:34 AM10/23/17
to Python Programming for Autodesk Maya

This is how my code looks like:
import socket
import select

class ChatServer:

    def __init__( self):
        self.port = 8880;
        self.srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
        self.srvsock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
        self.srvsock.bind( ("", 8880) )
        self.srvsock.listen( 5 )
        print("New socket bind")
        while 1:
            print("Waiting for new connection")
            self.sock,(remhost,remport)=self.accept_new_connection()
        print ('ChatServer started on port %s' % port)

    def send(self,data):
        self.sock.send(data)
    def receieve(self):
        self.str=sock.recv(1024)
        print(self.str)


I want to run this code first time when my project starts and want to call send() and receive() functions from other two different python files located in different path.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.

Justin Israel

unread,
Oct 23, 2017, 3:29:01 PM10/23/17
to python_in...@googlegroups.com


On Tue, Oct 24, 2017, 1:32 AM T Obulesu <obul...@gmail.com> wrote:

This is how my code looks like:
import socket
import select

class ChatServer:

    def __init__( self):
        self.port = 8880;
        self.srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
        self.srvsock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
        self.srvsock.bind( ("", 8880) )
        self.srvsock.listen( 5 )
        print("New socket bind")
        while 1:
            print("Waiting for new connection")
            self.sock,(remhost,remport)=self.accept_new_connection()
        print ('ChatServer started on port %s' % port)

    def send(self,data):
        self.sock.send(data)
    def receieve(self):
        self.str=sock.recv(1024)
        print(self.str)


I want to run this code first time when my project starts and want to call send() and receive() functions from other two different python files located in different path.
 

Looks like what you want is for your ChatServer to be one class that has the responsibility of accepting socket connections, receiving, and sending for all connected clients. And then you want another class that is a ChatClient which allows a connection to the chat server on port 8880 and let's the client to send and receive messages. Does that sound like the goal? Or are you trying to just establish a bi-directional request/reply between two peers? 

Is this a simplified version of your code or the actual code you are running? There are some issues with this code. 

It starts binding and listening immediately in the constructor with no way to stop it. I would suggest moving it to a start method and adding a way to stop it. Even once you do that, it blocks the thread while accepting connections. Is that what you want or are you running this chat server in another thread?

While it is accepting connections it constantly replaces the last connection with the next one. Is that what you are after? You have set the listen to 5 so it implies you expect multiple clients. But nothing is set up to handle each individual connection. I would expect that you are either going to handle a single connection at a time in that same thread,  or to hand off the connection to a thread, or to use a select operation to handle accepting new connections and servicing existing ones asynchronously in the same thread. 

Can you explain what the role is, for the other two modules that want to use this ChatServer? Are they meant to be clients that can chat to each other? Or is one trying to send data and the other is trying to receive? Can you describe your expected workflow so I can better understand how each of those other modules should actually be using this ChatServer to achieve their goal? 

To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/be550507-7ccd-4a99-bd56-cebfda87f24f%40googlegroups.com.

T Obulesu

unread,
Oct 24, 2017, 2:44:44 AM10/24/17
to Python Programming for Autodesk Maya


On Tuesday, 24 October 2017 00:59:01 UTC+5:30, Justin Israel wrote:


On Tue, Oct 24, 2017, 1:32 AM T Obulesu <obul...@gmail.com> wrote:

This is how my code looks like:
import socket
import select

class ChatServer:

    def __init__( self):
        self.port = 8880;
        self.srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
        self.srvsock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
        self.srvsock.bind( ("", 8880) )
        self.srvsock.listen( 5 )
        print("New socket bind")
        while 1:
            print("Waiting for new connection")
            self.sock,(remhost,remport)=self.accept_new_connection()
        print ('ChatServer started on port %s' % port)

    def send(self,data):
        self.sock.send(data)
    def receieve(self):
        self.str=sock.recv(1024)
        print(self.str)


I want to run this code first time when my project starts and want to call send() and receive() functions from other two different python files located in different path.
 

Looks like what you want is for your ChatServer to be one class that has the responsibility of accepting socket connections, receiving, and sending for all connected clients. And then you want another class that is a ChatClient which allows a connection to the chat server on port 8880 and let's the client to send and receive messages. Does that sound like the goal? Or are you trying to just establish a bi-directional request/reply between two peers? 

    Exactly. I want ChatServer to be the class where 1.connection establishment(), 2.data sending() and 3.data receiving()  should be resided.

When I run my project main file, (which is not actually the Chatserver), connection establishment(it can be a constructor or a function) of the ChatServer should run first.
Once connection is established, another python code should send the data through the established connection. Hence it should be able to access/override the data sending () function og the ChatServer(which means that i am not sending the data directly using ChatServer Function but some other files are importing it and sending the data)
Similarly, when the client sends the data, it's not the ChatServer which is receiving the data but another python file which imports this ChatServer and modifies the data_receiving() function.

To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.

Justin Israel

unread,
Oct 24, 2017, 7:24:31 AM10/24/17
to python_in...@googlegroups.com
I figured it would be more helpful if I just threw together some quick code so we have something tangible to discuss. It may not be what you are after. Also I have never yet used the asyncio features of Python3 so I cobbled together an asyncore approach, which contains backwards support for python 2.x via threading.


So to break down what this is doing, I have created the ChatServer class which takes care of setting up the server socket. And I have created a hook for a reader to be able to set their callback function when data is ready to be read from the socket. This would allow one of your other programs to set its own callback. 

You can see at the bottom of the script that I create a reader and a writer class to mimick what you described as two other programs. One sets itself as the reader for the server and uses composition instead of inheritence. It doesn't inherit from the ChatServer. Then the writer class is dead simple and just connects and provides a send() method. Note there is very little error handling anywhere as it is just a test.

Usage:

# in one shell
$ python server.py

# in another shell
$ echo "hello" | nc localhost 8080
ECHO: hello

Is this the idea you were after? I am sure there are other ways to go about this, either by using the new asyncio stuff, or by making it completely threaded. This current implementation at least can handle multiple writers connecting and sending data to a single reader.

Justin


To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/38035268-5d27-416b-982e-4d1607177000%40googlegroups.com.

T Obulesu

unread,
Nov 6, 2017, 2:51:34 AM11/6/17
to Python Programming for Autodesk Maya
Hello Justin,
Thanks a lot for your information.
It's really helpful.
I solved this using a singleton pattern.

My final code looks like this:


Desktop/Server.py


import socket
import logging
import pickle

class reception_eth:
    __instance = None
    #sock=None
    __name__ = "serial.reception"
    logger = logging.getLogger(__name__)
    @staticmethod
    def getInstance():
        """ Static access method. """
        if reception_eth.__instance == None:
            print(reception_eth.__instance)
            reception_eth()
        return reception_eth.__instance

    def __init__(self):
        if reception_eth.__instance != None:
            print(reception_eth.__instance)
            #reception_eth.__instance = self
            #raise Exception("This class is a singleton!")
        else:
            reception_eth.__instance = self
            self.initialise()

    def initialise(self):
        try:
            self.port = 8880;
            self.srvsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.srvsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.srvsock.bind(("", 8880))
            print("New socket bind")
            self.srvsock.listen(5)
            print("Status")
            print("Waiting for new connection")
            self.sock, (remhost, remport) = self.srvsock.accept()
            #print ("connection %s" %sock)
            #         print('ChatServer started on port %s' % self.port)
        except socket.error as e:
            print(e)

    # def start_serial(self):
    #     while True:
    #         print("***********Waiting for the data")
    #         self.message = self.sock.recv(1024).decode('utf-8')
    #         print("Receieved Packet is: "+str(self.message))
    #         decapsulation.decaptulation(self.message)

    def send(self, data, destination):
        print(data)
        self.sock.send(pickle.dumps(data))
        print("Sent")




And I'm calling the send function from many other python files (located in different paths) by creating an object.
Here, This will not throw the error, "Port is already in use" since only one object is created and shared by other files,


On Tuesday, 24 O
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.

Justin Israel

unread,
Nov 6, 2017, 5:24:21 AM11/6/17
to python_in...@googlegroups.com
Be careful with this approach. I don't think a socket is thread safe. You are accepting one connection and not starting any kind of handler to ensure it keeps reading. And if you are it sounds like you must be doing that in another thread. That means you have multiple threads doing read and writes to a single socket. 

But if you are happy with your results, then glad you got something working! 

To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/630d439f-d4cc-4989-b4cb-13c2c1d47dc6%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages