Esempio n. 1
0
def main():
    # set up logger
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s:%(levelname)s:%(message)s')

    # initalize chat server instance
    logging.debug("Initialize chat server")
    server = ChatServer()

    # set up handler for processing outgoing messages
    # TODO: add support for more threads, only necessary if heavy load. So probably will never do this.
    logging.debug(f"Setting up handler for processing outgoing messages")
    t = Thread(target=server.process_outgoing_messages)
    t.setDaemon(True)
    t.start()

    # set up handler for processing outgoing messages
    # TODO: add support for more threads, only necessary if heavy load. So probably will never do this.
    logging.debug(f"Setting up handler for processing incoming messages")
    t = Thread(target=server.process_incoming_messages)
    t.setDaemon(True)
    t.start()

    # spawn a thread to handle send/recv for each connection we receive
    while True:
        try:
            # handle_connections waits for new connections, if the function returns we create a thread to handle
            # the new connection. Then we wait for another one.
            t = Thread(target=server.handle_connections,
                       args=(server.get_connections(), ))
            t.setDaemon(True)
            t.start()
        except KeyboardInterrupt:
            print('Bye.')
            exit(1)
Esempio n. 2
0
def chat_server_thread(port, pri):
    print("[Server] Private: ", pri)
    exchange_server = ExchangeServer(port, pri)
    sym_key = exchange_server.serve()
    print("[Server] sym_key: ", sym_key)

    chat_server = ChatServer(port, sym_key)
    chat_server.serve()
Esempio n. 3
0
    def setUp(self):
        """
        Sets up the test environment by running a new ChatServer thread.
        """
        self.chat_server = ChatServer(self.HOST, self.PORT)
        self.chat_server.start()

        time.sleep(1)  # Gives the client the time for connecting to the server
Esempio n. 4
0
class ChatTest(unittest.TestCase):
    def setUp(self):
       self.transport = proto_helpers.FakeDatagramTransport()
       self.server = ChatServer(prompt=MockedPrompt())
       self.server.transport = self.transport         

    def test_punchHole(self):
        self.server.datagramReceived('PUNCH', FAKE_ENDPOINT)
        resp, addr = self.transport.written[0]
        self.assertEqual(addr, FAKE_ENDPOINT)
        self.assertEqual(resp, 'HOLED')

    def test_broadcasteMessage(self):
        buddy = generate_endpoint()
        destination = [generate_endpoint() for x in xrange(10)]

        #   conect clients
        self.server.datagramReceived('CONNECT|127.0.0.1|3000|Buddy', buddy)        
        for d in destination:
            self.server.datagramReceived('CONNECT|127.0.0.1|3000|RandomName', d)

        #   post a message
        line = generate_string(20)
        self.server.datagramReceived('MSG|%s' % line, buddy)

        #   check message received by others
        broadcasted_line = 'MSG|Buddy|%s' % line
        for d in destination:
            self.assertTrue((broadcasted_line, d) in self.transport.written)
Esempio n. 5
0
    port = DEFAULT_PORT
    server_address = DEFAULT_SERVER_IP_LISTENING_ADDRESS
    # TODO: Edit code for working with console keys -address, -port
    # or find out library
    if len(sys.argv) > 1:
        # TODO: Create a function with code from 'else'
        key1 = sys.argv[1]
        if key1 == '-p':
            try:
                port = int(sys.argv[2])
            except ValueError:
                print('Port should be integer number')
                sys.exit(0)
        elif key1 == '-a':
            try:
                server_address = sys.argv[2]
            except ValueError:
                print('Value error in server address')
                sys.exit(0)
    return port, server_address


logging.basicConfig(stream=sys.stdout, level=logging.INFO)

port, server_address = parse_command_line()
chat_server = ChatServer(server_address, port)
sock = chat_server.connect()
if __debug__:
    logging.info('Set port to {}'.format(port))
chat_server.listen_for_good()
Esempio n. 6
0
import logging

from cyber import options
from chat_protocol import ChatProtocol
from chat_server import ChatServer, ChatClient
from cyber import server_logger, client_logger

if __name__ == '__main__':
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    server_logger.setLevel(logging.DEBUG)
    client_logger.setLevel(logging.DEBUG)
    server_logger.addHandler(ch)
    client_logger.addHandler(ch)
    options.load_yaml("chat2.yaml")
    protocol = ChatProtocol(2, ">H")
    chat_server = ChatServer(protocol, ChatClient)
    chat_server.impl(options)
    chat_server.run()
Esempio n. 7
0
        start_new_thread(listen_users, (server, connection))
        server.send_mensage(
            json.dumps({
                'mensagem': f'{nickname} entrou no servidor',
                'nickname': 'Server'
            }).encode())


def listen_users(server, connection):
    while True:
        mensagem = connection.recv(1024)
        if not mensagem:
            connection.close()
        else:
            value = server.verify_mensage(connection, mensagem)
            if value == 1:
                server.send_mensage(mensagem)
            if value == 2:
                connection.close()
                break


server = ChatServer()

server.server_socket.bind(('127.0.0.1', 65432))
server.server_socket.listen(1)

t_1 = threading.Thread(target=add_users(server))

t_1.start()
Esempio n. 8
0
# -*- coding:utf-8 -*-
"""
Created on 19/06/2017

@author: zhaojm
"""

import os
import sys

current_path = os.path.dirname(os.path.abspath(__file__))
source_path = os.path.join(current_path, "../../")
sys.path.append(source_path)

from chat_server import ChatServer
from core.reactor import start_reactor
from core.factory import init_server

s = ChatServer()
init_server(s)
start_reactor()
Esempio n. 9
0
 def setUp(self):
    self.transport = proto_helpers.FakeDatagramTransport()
    self.server = ChatServer(prompt=MockedPrompt())
    self.server.transport = self.transport         
Esempio n. 10
0
from chat_server import ChatServer
from chat_client import ChatClient
from config import Config, LoadFromArgparse, LoadFromConsole, LoadFromFile, LoadFromParams

if __name__ == "__main__":

    config = Config(LoadFromParams())

    server = ChatServer(config.get_dict_config())

    server.send_message(b"Hello")
Esempio n. 11
0
import sys
from chat_server import ChatServer
import time

#The line means that we allow you to connect with any host (any IP and Hostname).
#You can explicitly write a localhost or 127.0.0.1, then it will only work on one computer.
server = ChatServer(5000, '10.40.27.236')
server.start()

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    server.stop()

Esempio n. 12
0
class ChatServerTest(unittest.TestCase):
    """
    Provides tests for the ChatServer application.
    """

    HOST = _HOST
    PORT = _PORT
    RECV_BUFFER = _RECV_BUFFER
    RECV_MSG_LEN = _RECV_MSG_LEN

    def setUp(self):
        """
        Sets up the test environment by running a new ChatServer thread.
        """
        self.chat_server = ChatServer(self.HOST, self.PORT)
        self.chat_server.start()

        time.sleep(1)  # Gives the client the time for connecting to the server

    def _get_fake_client(self):
        """
        Returns a fake client.

        :return: a socket connected with the known (host, port) pair
        """
        fake_client = socket.socket()
        fake_client.settimeout(1)
        fake_client.connect((self.HOST, self.PORT))
        return fake_client

    def test_connection(self):
        """
        Tests the client-server connection.
        """
        fake_client = self._get_fake_client()
        fake_client.close()

    def _get_enter_message(self, socket_name):
        """
        Given the pair (host, port), returns the message the server should broadcast
        to all the clients each time a new client connects.

        :param socket_name: the (host, port) pair related to the client connection
        :return: the message broadcast by the server when a new client connects
        """
        return "\n[%s:%s] entered the chat room\n" % socket_name

    def _get_broadcast_message(self, socket_name, msg):
        """
        Given the pair (host, port) and a message, returns the message the server should
        broadcast to all the clients.

        :param socket_name: the (host, port) pair related to the client connection
        :param msg: the message sent by the client
        :return: the message broadcast by the server
        """
        return "\r" + '<' + str(socket_name) + '> ' + msg

    def _get_packed_length(self, msg):
        """
        Given a message, return its packed length.

        :param msg: the message
        :return: the packed length of the message
        """
        return struct.pack('>I', len(msg))

    def test_broadcast(self):
        """
        Tests the message broadcasting performed by the server.
        """
        fc1 = self._get_fake_client()  # The first client connects

        fc2 = self._get_fake_client()  # The second client connects
        fc2_enter_msg = self._get_enter_message(fc2.getsockname())
        fc2_msg_pack_len = self._get_packed_length(fc2_enter_msg)
        self.assertEqual(fc1.recv(self.RECV_MSG_LEN), fc2_msg_pack_len)
        self.assertEqual(fc1.recv(self.RECV_BUFFER), fc2_enter_msg)

        fc3 = self._get_fake_client()  # The third client connects
        fc3_enter_msg = self._get_enter_message(fc3.getsockname())
        fc3_msg_pack_len = self._get_packed_length(fc3_enter_msg)
        self.assertEqual(fc1.recv(self.RECV_MSG_LEN), fc3_msg_pack_len)
        self.assertEqual(fc1.recv(self.RECV_BUFFER), fc3_enter_msg)
        self.assertEqual(fc2.recv(self.RECV_MSG_LEN), fc3_msg_pack_len)
        self.assertEqual(fc2.recv(self.RECV_BUFFER), fc3_enter_msg)

        fc3_orig_msg = 'Hello'
        fc3_orig_msg_packed_len = self._get_packed_length(fc3_orig_msg)
        fc3.send(fc3_orig_msg_packed_len +
                 fc3_orig_msg)  # The third client sends a message
        fc3_broadcast_msg = self._get_broadcast_message(
            fc3.getsockname(), fc3_orig_msg)
        fc3_broadcast_msg_pack_len = self._get_packed_length(fc3_broadcast_msg)
        self.assertEqual(fc1.recv(self.RECV_MSG_LEN),
                         fc3_broadcast_msg_pack_len)
        self.assertEqual(fc1.recv(self.RECV_BUFFER), fc3_broadcast_msg)
        self.assertEqual(fc2.recv(self.RECV_MSG_LEN),
                         fc3_broadcast_msg_pack_len)
        self.assertEqual(fc2.recv(self.RECV_BUFFER), fc3_broadcast_msg)

        fc1.close()
        fc2.close()
        fc3.close()

    def test_heavy_broadcast(self):
        """
        Tests the message broadcasting performed by the server when big
        messages are involved.
        """
        fc1 = self._get_fake_client()  # The first client connects

        fc2 = self._get_fake_client()  # The second client connects
        fc2_enter_msg = self._get_enter_message(fc2.getsockname())
        fc2_msg_pack_len = self._get_packed_length(fc2_enter_msg)
        self.assertEqual(fc1.recv(self.RECV_MSG_LEN), fc2_msg_pack_len)
        self.assertEqual(fc1.recv(self.RECV_BUFFER), fc2_enter_msg)

        fc2_orig_msg = os.urandom(10000)  # Creates a message of 10000 bytes
        fc2_orig_msg_packed_len = self._get_packed_length(fc2_orig_msg)
        fc2.send(fc2_orig_msg_packed_len +
                 fc2_orig_msg)  # The second client sends an heavy message
        fc2_broadcast_msg = self._get_broadcast_message(
            fc2.getsockname(), fc2_orig_msg)
        fc2_broadcast_msg_pack_len = self._get_packed_length(fc2_broadcast_msg)
        self.assertEqual(fc1.recv(self.RECV_MSG_LEN),
                         fc2_broadcast_msg_pack_len)

        fc2_receipt_message = ''
        for _ in xrange(
                3
        ):  # Expecting 3 chunks of 4096 bytes ( ceil [10000 bytes / 4096 bytes] = 3 )
            fc2_receipt_message += fc1.recv(self.RECV_BUFFER)
        self.assertEqual(fc2_receipt_message, fc2_broadcast_msg)

        fc1.close()
        fc2.close()

    def tearDown(self):
        """
        Clears the test environment by stopping the server.
        """
        time.sleep(
            1)  # Gives the client the time for disconnecting from the server
        self.chat_server.stop()
Esempio n. 13
0
def listen(port):
    click.echo('starting chat server at {}'.format(port))
    chat_server = ChatServer(port=port)
    chat_server.start()
Esempio n. 14
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from sys import argv

from chat_server import ChatServer

server = ChatServer()

try:
    server.set_port(int(argv[1]))
except ValueError:
    pass
except IndexError:
    pass

try:
    server.run()
except KeyboardInterrupt:
    server.stop()
Esempio n. 15
0
from chat_client import ChatClient
from chat_server import ChatServer
import time

class ChatApp():
	def __init__(self):
		self.server = ChatServer()
		self.client = ChatClient()

	def setup():
		pass


if __name__ == "__main__":
	server = ChatServer()
	clients = [ChatClient() for i in range(5)]
	server.start()
	for c in clients:
		c.connect()
	for c in clients:
		c.say_hello()
	time.sleep(3)
	server.stop()
Esempio n. 16
0
#!/usr/bin/python3
import connect_util
from chat_server import ChatServer
from chat_client import ChatClient
import argparse


if __name__ == '__main__':
    """
        Example (foreach terminal):
        Server: python3 2_3_chat_server_with_select --name server --port 1234
        Client1: python3 2_3_chat_server_with_select --name client1 --port 1234
        Client2: python3 2_3_chat_server_with_select --name client2 --port 1234
    """
    parser = argparse.ArgumentParser(
        description='Socket server Example with Select')
    parser.add_argument('--name', action='store', dest='name', required=True)
    parser.add_argument(
        '--port', action='store', dest='port', type=int, required=True)
    given_args = parser.parse_args()
    port = given_args.port
    name = given_args.name
    if name == connect_util.CHAT_SERVER_NAME:
        server = ChatServer(port)
        server.run()
    else:
        client = ChatClient(name=name, port=port)
        client.run()
Esempio n. 17
0
from chat_server import ChatServer
from twisted.internet import reactor

if __name__ == '__main__':
    reactor.listenTCP(9399, ChatServer())
    reactor.run()