Differences between revisions 1 and 2
Revision 1 as of 2005-10-20 08:31:03
Size: 765
Editor: Chaox
Comment:
Revision 2 as of 2005-11-11 04:19:07
Size: 6389
Editor: Chaox
Comment:
Deletions are marked like this. Additions are marked like this.
Line 26: Line 26:
'''新写了一个基于C/S的聊天工具,用了Threading,Tkinter,socket 等'''
Server :
{{{#!python
# -------------------------------------------------
# set up a server that will receive a connection
# from a client, send a string to the client
# and close the connection
# Created by Chao Xiong 2005.Oct.
# Version 1.1
# -------------------------------------------------

import socket
import threading

HOST = ""
PORT = 4000
# HOST = raw_input("Pls input the IP address of host: ")
# PORT = int(raw_input("Pls input the port of host: "))
# clientcounter = 1
clientnumber = 2
clients = []
buf = 1024

class client(threading.Thread):
    def __init__(self, server, ID):

        threading.Thread.__init__(self)
        self.connection = connections[ID]
        # self.friendcon = connection[1-ID]
        self.server = server
        self.ID = ID
        # self.friendID = 1 - ID

    def run(self):
        friendMessage = ""
        self.connection.send("Welcome to the Server! Client %s" % self.ID)
        friendMessage = self.connection.recv(buf)
        while 1:
            
            if friendMessage != "":
                for con in connections:
                    con.send("Client %s : " % self.ID + friendMessage)
                # self.connection.send("Client %s : " % self.ID + friendMessage)
                # self.friendcon.send("Client %s : " % self.ID + friendMessage)
                print "Client %s : " % self.ID + friendMessage
                friendMessage = ""
            try:
                friendMessage = self.connection.recv(buf)
            except:
                print "Client %s is quit" % self.ID
                break
                            
                
class ChatServer:
    def __init__(self):
        self.HOST = ""
        self.PORT = 4000
        self.address = (self.HOST, self.PORT)

        self.clientcounter = 0

        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind(self.address)
        self.display("Waiting for connection...")
        self.execute()

    def execute(self):
        self.clients = []
        global connections
        connections = []
        destination = []
        Id = 0

        while 1:
            self.server.listen(clientnumber)
            con, dest = self.server.accept()
            connections.append(con)
            destination.append(dest)
            self.clientcounter += 1
            self.clients.append(client(self.server, Id))
            self.clients[Id].start()
            # self.clients[i].run()
            self.display("Client%s is connected" % Id)
            Id += 1

    def display(self, message):
        print message

def main():
    ChatServer().execute()

if __name__ == "__main__":
    main()
}}}

Client :
{{{#!python
# ---------------------------------
# chatting tools Client GUI
# Created by Chao Xiong 2005.Oct
# version 1.0
# ---------------------------------

from Tkinter import *
import Pmw
import threading
import socket

buf = 1024

class ChatClient(Frame, threading.Thread):
    """A simple GUI for client"""

    def __init__(self, name = "newcomer"):
        """initialize the frame"""

        self.name = name
        self.thecontents = ""

        threading.Thread.__init__(self)
        Frame.__init__(self)
        self.pack(expand = YES, fill = BOTH)
        # self.master.title("Chatting %s" % self.name)
        self.master.title("Chatting %s" % self.name)
        self.master.geometry("400x300")

        self.chatting = Entry(self)
        self.chatting.pack(fill = X, padx = 5, pady = 5)
        self.chatting.bind("<Return>", self.sendmessage)

        self.contents = Pmw.ScrolledText(self, text_state = DISABLED)
        self.contents.pack(expand = NO, fill = BOTH, padx = 5, pady = 5)

        self.start()

    def sendmessage(self, event):
        
        self.thecontents = event.widget.get()
        if self.thecontents != "":
            self.chatting.delete(0,len(self.thecontents))
            self.connection.send(self.thecontents)
            
            

    def displaymessage(self, message):
        self.contents.text_state = NORMAL
        self.contents.appendtext(message)
        self.contents.appendtext("\n")
        self.contents.text_state = DISABLED

    def run(self):
        HOST = "127.0.0.1"
        PORT = 4000
        address = (HOST, PORT)

        self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.connection.connect(address)
        except:
            self.displaymessage("Call failed")
            
        serverMessage = self.connection.recv(buf)

        while 1:
            
            if serverMessage != "":
                self.displaymessage(serverMessage)
                serverMessage = ""

            try:
                serverMessage = self.connection.recv(buf)
            except:
                self.displaymessage("The Server is shut down!")
                break
            

        self.connection.close()

    
        
def main():
    ChatClient().mainloop()

if __name__ == "__main__":
    main()


}}}

长是长了点,有些是废话。。。。

'''有个问题请教各位高手,现在在Windows下执行以上两段程序时(直接双击),除了出现
Tkinter的窗口界面外,还会出现一个DOS窗口,不知怎么去掉这个DOS窗口??谢谢!'''
Line 32: Line 225:
''欢迎大家对你说三道四哪'' ''欢迎大家浇水啊!''

中文Python行者首页 文章模板

-- Chaox (Date(2005-10-20T08:31:03Z)) TableOfContents

1. 关于我

个人信息

Chaox

邮件

[email protected]

工作电话

移动电话

UC 号码

MSN

[email protected]

1.1. 工作日志

MonthCalendar

日志内容提要Include(^UrPageName/.*,'日志简报',4,sort=descending,items=30,titlesonly)

1.2. 能力自述

刚刚开始学Python,希望聆听和参与大家的讨论

1.2.1. 技术

新写了一个基于C/S的聊天工具,用了Threading,Tkinter,socket 等 Server :

   1 # -------------------------------------------------
   2 # set up a server that will receive a connection
   3 # from a client, send a string to the client
   4 # and close the connection
   5 # Created by Chao Xiong 2005.Oct.
   6 # Version 1.1
   7 # -------------------------------------------------
   8 
   9 import socket
  10 import threading
  11 
  12 HOST = ""
  13 PORT = 4000
  14 # HOST = raw_input("Pls input the IP address of host: ")
  15 # PORT = int(raw_input("Pls input the port of host: "))
  16 # clientcounter = 1
  17 clientnumber = 2
  18 clients = []
  19 buf = 1024
  20 
  21 class client(threading.Thread):
  22     def __init__(self, server, ID):
  23 
  24         threading.Thread.__init__(self)
  25         self.connection = connections[ID]
  26         # self.friendcon = connection[1-ID]
  27         self.server = server
  28         self.ID = ID
  29         # self.friendID = 1 - ID
  30 
  31     def run(self):
  32         friendMessage = ""
  33         self.connection.send("Welcome to the Server! Client %s" % self.ID)
  34         friendMessage = self.connection.recv(buf)
  35         while 1:
  36             
  37             if friendMessage != "":
  38                 for con in connections:
  39                     con.send("Client %s : " % self.ID + friendMessage)
  40                 # self.connection.send("Client %s : " % self.ID + friendMessage)
  41                 # self.friendcon.send("Client %s : " % self.ID + friendMessage)                
  42                 print "Client %s : " % self.ID + friendMessage
  43                 friendMessage = ""
  44             try:
  45                 friendMessage = self.connection.recv(buf)
  46             except:
  47                 print "Client %s is quit" % self.ID
  48                 break
  49                             
  50                 
  51 class ChatServer:
  52     def __init__(self):
  53         self.HOST = ""
  54         self.PORT = 4000
  55         self.address = (self.HOST, self.PORT)
  56 
  57         self.clientcounter = 0
  58 
  59         self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  60         self.server.bind(self.address)
  61         self.display("Waiting for connection...")
  62         self.execute()
  63 
  64     def execute(self):
  65         self.clients = []
  66         global connections
  67         connections = []
  68         destination = []
  69         Id = 0
  70 
  71         while 1:
  72             self.server.listen(clientnumber)
  73             con, dest = self.server.accept()
  74             connections.append(con)
  75             destination.append(dest)
  76             self.clientcounter += 1
  77             self.clients.append(client(self.server, Id))
  78             self.clients[Id].start()            
  79             # self.clients[i].run()
  80             self.display("Client%s is connected" % Id)
  81             Id += 1
  82 
  83     def display(self, message):
  84         print message
  85 
  86 def main():
  87     ChatServer().execute()
  88 
  89 if __name__ == "__main__":
  90     main()

Client :

   1 # ---------------------------------
   2 # chatting tools Client GUI
   3 # Created by Chao Xiong 2005.Oct
   4 # version 1.0
   5 # ---------------------------------
   6 
   7 from Tkinter import *
   8 import Pmw
   9 import threading
  10 import socket
  11 
  12 buf = 1024
  13 
  14 class ChatClient(Frame, threading.Thread):
  15     """A simple GUI for client"""
  16 
  17     def __init__(self, name = "newcomer"):
  18         """initialize the frame"""
  19 
  20         self.name = name
  21         self.thecontents = ""
  22 
  23         threading.Thread.__init__(self)
  24         Frame.__init__(self)
  25         self.pack(expand = YES, fill = BOTH)
  26         # self.master.title("Chatting %s" % self.name)
  27         self.master.title("Chatting %s" % self.name)
  28         self.master.geometry("400x300")
  29 
  30         self.chatting = Entry(self)
  31         self.chatting.pack(fill = X, padx = 5, pady = 5)
  32         self.chatting.bind("<Return>", self.sendmessage)
  33 
  34         self.contents = Pmw.ScrolledText(self, text_state = DISABLED)
  35         self.contents.pack(expand = NO, fill = BOTH, padx = 5, pady = 5)
  36 
  37         self.start()
  38 
  39     def sendmessage(self, event):
  40         
  41         self.thecontents = event.widget.get()
  42         if self.thecontents != "":
  43             self.chatting.delete(0,len(self.thecontents))
  44             self.connection.send(self.thecontents)            
  45             
  46             
  47 
  48     def displaymessage(self, message):
  49         self.contents.text_state = NORMAL
  50         self.contents.appendtext(message)
  51         self.contents.appendtext("\n")
  52         self.contents.text_state = DISABLED
  53 
  54     def run(self):
  55         HOST = "127.0.0.1"
  56         PORT = 4000
  57         address = (HOST, PORT)
  58 
  59         self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  60         try:
  61             self.connection.connect(address)
  62         except:
  63             self.displaymessage("Call failed")
  64             
  65         serverMessage = self.connection.recv(buf)
  66 
  67         while 1:
  68             
  69             if serverMessage != "":               
  70                 self.displaymessage(serverMessage)
  71                 serverMessage = ""
  72 
  73             try:
  74                 serverMessage = self.connection.recv(buf)
  75             except:
  76                 self.displaymessage("The Server is shut down!")
  77                 break
  78             
  79 
  80         self.connection.close()
  81 
  82     
  83         
  84 def main():
  85     ChatClient().mainloop()
  86 
  87 if __name__ == "__main__":
  88     main()

长是长了点,有些是废话。。。。

有个问题请教各位高手,现在在Windows下执行以上两段程序时(直接双击),除了出现 Tkinter的窗口界面外,还会出现一个DOS窗口,不知怎么去掉这个DOS窗口??谢谢!

1.2.2. 知识

1.2.3. 等等

2. 反馈

欢迎大家浇水啊!

Chaox (last edited 2009-12-25 07:15:53 by localhost)