1. Cédric Bonhomme
  2. GoTalk

Source

GoTalk / client.py

#! /usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = "Cedric Bonhomme"
__version__ = "$Revision: 0.1 $"
__date__ = "$Date: 2009/12/02 $"
__revision__ = "$Date: 2012/12/30 $"
__copyright__ = "Copyright (c) Cedric Bonhomme"
__license__ = "GPLv3"


import socket
import threading

class Client(object):
    """
    Python client.
    """
    def __init__(self, adresseDistante, portDistant):
        """
        Connect to the server.
        """
        self.adresseDistante = adresseDistante
        self.portDistant = portDistant
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((self.adresseDistante, self.portDistant))

        self.lecture = threading.Thread(None, self.receive)
        #self.lecture.setDaemon(True)
        self.lecture.start()

        self.ecriture = threading.Thread(None, self.send)
        #self.ecriture.setDaemon(True)
        self.ecriture.start()
        self.ecriture.join()
        self.lecture.join()

    def receive(self):
        """
        Receive messages.
        """
        data = ""
        while True:
            try:
                data = self.sock.recv(1024)
            except socket.error as e:
                return
            if data:
                print(data.decode("utf-8"))

    def send(self):
        """
        Send messages.
        """
        message = input("Please give yourname: ")
        while message.strip() != "Q":
            self.sock.send(message.encode("utf-8"))
            message = input("you> ")
        self.sock.shutdown(socket.SHUT_RDWR)
        self.sock.close()

if __name__ == '__main__':
    # Point of entry in execution mode.
    client = Client('127.0.0.1', 9988)