from Tkinter import *
import tkMessageBox
import socket
import logging
import sys, time
import pickle
import thread



class ClientChat():
    def __init__(self,serverport):
        self.counter = 0

        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.host = 'localhost' # server address
        self.port = serverport # server port 

        # connect to server
        self.s.connect((self.host, self.port))

        self.chatclient = Tk()

        self.chatclient["padx"] = 200
        self.chatclient["pady"] = 200

        self.chatclient.title("Client")

        self.f1 = Frame(self.chatclient,width = 100, height = 10)
        self.f1.pack(side = TOP)

        self.f2 = Frame(self.chatclient,width = 100, height = 10)
        self.f2.pack(side = BOTTOM)

        
        self.recvmsg = Text(self.f1, width = 100, height = 10)
        self.sb = Scrollbar(self.f1)
        self.sb.pack(side = RIGHT, fill = Y)
        
        self.sb.config(command = self.recvmsg.yview)
        self.recvmsg.config(yscrollcommand=self.sb.set)
        self.recvmsg.pack(padx = 10, pady =10)

        self.sendmsg = Text(self.f2, width = 100, height = 5)
        self.sendmsg.pack(padx = 10, pady =20)

        self.sendbutton =Button(self.f2, width = 5, height = 2, text = "Send", command = self.senddata)
        self.sendbutton.pack(side = LEFT, padx = 10, pady = 10)

        self.sendbutton =Button(self.f2, width = 5, height = 2, text = "Exit", command = self.exitchat)
        self.sendbutton.pack(side = RIGHT, padx = 10, pady = 10)
        
        self.chatclient.mainloop()
        

    def senddata(self):
        self.k = self.sendmsg.get(1.0, END)
        self.sendmsg.delete(1.0, END)
        self.s.send(self.k)
            
        if self.counter == 0:
            thread.start_new_thread(self.recvdata,())
##        if self.k == '':
##            thread.exit()
##            self.s.close()
##            self.chatclient.destroy()

    def exitchat(self):
        self.s.close()
        self.chatclient.destroy()
        
    def recvdata(self):
        while 1:
            self.v = self.s.recv(1024) 
            self.recvmsg.insert(END,self.v)
            
                

if __name__ == '__main__':

    serverport = int(raw_input("Enter the server address:..."))
    c = ClientChat(serverport)
            

