Sunday, December 23, 2012

Learning Python - Half-Duplex Chat Server/Client

#!/usr/bin/env python

import sys
from socket import *

usage = "Usage: ./clientChat.py <Listening Port>"

if (len(sys.argv) > 1):
    LPORT = int(sys.argv[1])
else:
    sys.exit(usage)

LOCALHOST = ''
BUFSIZE = 1024
ADDR = (LOCALHOST, LPORT)

serverID = ''
portNumb = ''
       
tcpChatSocket = socket(AF_INET, SOCK_STREAM)
tcpChatSocket.bind(ADDR)
tcpChatSocket.listen(5)

chatID = raw_input('Enter you chat ID: ')
chatConversation = raw_input('"W" to wait for a connection, or press "I" to initiate a conversation. ')

while True:

    if chatConversation == "W":
        if serverID == '':
            print "Waiting for the connection..."
        tcpMySocket, ADDR = tcpChatSocket.accept()
        while True:
            data = tcpMySocket.recv(BUFSIZE)
            print data
            if not data:
                break
        chatConversation = "I"
    elif chatConversation == "I":
        if serverID == '':
            serverID = raw_input('Enter friends IP Address: ')
        if portNumb == '':
            portNumb = int(raw_input('Enter listening port for chat: '))
        tcpFriendSocket = socket(AF_INET, SOCK_STREAM)
        remoteADDR = (serverID, portNumb)
        tcpFriendSocket.connect(remoteADDR)
        chatData = raw_input('> ')
        if not chatData:
            break
        tcpFriendSocket.send('[%s] %s' % (chatID, chatData))
        tcpFriendSocket.close()   
        chatConversation = "W"

No comments:

Post a Comment

Test Authentication from Linux Console using python3 pexpect

Working with the IT420 lab, you will discover that we need to discover a vulnerable user account.  The following python3 script uses the pex...