コード例 #1
0
ファイル: get.py プロジェクト: sakib/cs352
def get(h, p, group):
    """
    takes user input from the command line and sends a message
    on host h and port p to required GROUPNAME
    """
    # print("sending a request to host {0} on port {1} to group {2}".\
    #        format(h, p, group))
    # os sys click datetime socket json struct string
    try:
        s.connect((h, p))
    except:
        print "Failed to connect to server on host {0}, port {1}".format(h, p)
        sys.exit(1)

    get_obj = {}
    get_obj['method'] = 'GET'
    get_obj['group'] = group

    # print("sending", get_obj)

    send_obj(get_obj, s)

    r = read_obj(s)

    if r['response'] != 'ok':
        print r['response']
        s.close()
        sys.exit(1)

    # print("--------------------")

    # Client should now receive messages

    r = read_obj(s)

    print len(r), " messages"
    for entry in r:
        print entry['header']
        print ""
        print entry['message']
        if r.index(entry) != len(r)-1:
            print ""

    s.close()                   # Close the socket when done
コード例 #2
0
ファイル: server.py プロジェクト: sakib/cs352
def server(p):

    s.bind(('localhost', p))        # Bind to the port
    s.listen(5)                 # Now wait for client connection, takes backlog - number of connections to queue
    while True:

        print('New server listening on port {0}'.format(p))
        c, addr = s.accept()     # Establish connection with client.

        resp_obj = {}

        try:
            # Validate method and socket
            thing = read_obj(c)
            if thing['method'] not in ['GET', 'POST']:
                resp_obj['response'] = "error: invalid command"
                send_obj(resp_obj, c)
                c.close()
        except:
            resp_obj['response'] = "error: failed to read from socket"
            send_obj(resp_obj, c)
            c.close()

        method = thing['method']
        group = thing['group']

        print("Got {} request from {} on port {} for group {}"\
                .format(method, addr[0], addr[1], group))

        if method == 'GET':             # Handle GET Request
            # Check for valid group
            if is_valid(group) and group in chat_groups:
                # print('Got group: ', group)
                resp_obj['response'] = "ok"
                send_obj(resp_obj, c)
            else:
                resp_obj['response'] = "error: invalid group name"
                send_obj(resp_obj, c)
                c.close()
                continue

            send_obj(chat_groups[group], c)

        elif method == 'POST':          # Handle POST Request
            try:
                # Check for valid group
                if is_valid(group):
                    # print('Got group: ', group)
                    resp_obj['response'] = "ok"
                    send_obj(resp_obj, c)
                else:
                    resp_obj['response'] = "error: invalid group name"
                    send_obj(resp_obj, c)
                    c.close()
                    continue

                # Now check for valid user
                thing = read_obj(c)
                id = thing['id']
                ip = addr[0]
                port = addr[1]

                if is_valid(id):
                    # print('Got ID: ', id)
                    resp_obj['response'] = "ok"
                    send_obj(resp_obj, c)
                else:
                    resp_obj['response'] = "error: invalid user name"
                    send_obj(resp_obj, c)
                    c.close()
                    continue

                # Now grab message from user
                thing = read_obj(c)
                msg = thing['_msg']

                # Initialize group in dict if it's new
                if not group in chat_groups:
                    chat_groups[group] = []

                # Create and record a post log
                post = {}
                post['header'] = "From {0} /{1}:{2} {3}"\
                    .format(id, addr[0], addr[1],
                            datetime.datetime.now().\
                            strftime('%a %b %d %H:%M:%S EST %Y'))
                post['message'] = msg

                chat_groups[group].append(post)

                # print "--------------"
                # print str(chat_groups)

            except Exception as e:
                print('something went wrong, maybe the client connection closed. ', e)

            # Finally, close the connection
            c.close()
コード例 #3
0
ファイル: post.py プロジェクト: sakib/cs352
def post(h, p, group):
    """
    takes user input from the command line
    sends a message on host h and port p
    to required GROUPNAME
    """

    # print("sending a request to host {0} on port {1} to group {2}"\
    #       .format(h, p, group))

    try:
        s.connect((h, p))           # Connect to server
    except:
        print "Failed to connect to server on host {0}, port {1}".format(h, p)
        sys.exit(1)

    post_obj = {}               # Create message
    post_obj['method'] = 'POST'
    post_obj['group'] = group

    # print('sending', post_obj)

    send_obj(post_obj, s)       # Send message over socket s

    r = read_obj(s)             # Read socket for "OK" or "Error"

    if r['response'] != 'ok':
        print r['response']
        s.close()
        sys.exit(1)

    # print "----------------"

    id = getpass.getuser()          # Get username
    post_obj['id'] = id

    # print('sending', post_obj)

    send_obj(post_obj, s)

    r = read_obj(s)             # Read socket for "OK" or "Error"

    if r['response'] != 'ok':
        # print r['response']
        s.close()
        sys.exit(1)

    # print "----------------"

    print "Please enter a message: "

    _msg = raw_input('')

    post_obj['_msg'] = _msg
    # print('sending', post_obj)

    send_obj(post_obj, s)

    print('message client finished')

    s.close()                   # Close the socket when done