stone

python-chatroom
在实验楼中看到一个用python tkintor实现带GUI的聊天室,跟着做了一下,当是重新熟悉一下python。...
扫描右侧二维码阅读全文
20
2016/11

python-chatroom

在实验楼中看到一个用python tkintor实现带GUI的聊天室,跟着做了一下,当是重新熟悉一下python。

我看的教程应该用的是python2,但是我用的是python3,其中socket程序中的输入输出都应该为byte,不应该为str,所以需要进行编码和解码才能进行传输

下面是一些代码,基本照抄了实验楼上的程序:

客户端:

import socket
import threading
import time

from tkinter import *

class ChatServer:
    def __init__(self):
        window = Tk()
        window.title("ChatClient")
        self.text = Text(window)
        self.text.pack()
        frame1 = Frame(window)
        frame1.pack()
        label = Label(frame1,text="Enter your Message:")
        self.Message =StringVar()
        entryMessage = Entry(frame1,textvariable=self.Message)
        btSend= Button(frame1,text="Send",
                       command=self.processSendButton)
        btLink = Button(window,text="Link",
                        command=self.processLinkButton)
        btLink.pack()

        label.grid(row=1,column=1)
        entryMessage.grid(row=1,column=2)
        btSend.grid(row=1,column =4)
        self.text.insert(END,"\t\t\t\t------------\n\t\t\t\tWelcome to Chat \n\t\t\t\
        Enjoy yourself \n\t\t\t\t--------\n\n\n")
        window.mainloop()
        print("success init")

    def processSendButton(self):
        self.s.send(self.Message.get().encode())
        self.text.insert(END,"[You Message]:"+self.Message.get()+"\n")

    def processLinkButton(self):
        self.s = socket.socket()
        host = socket.gethostname()
        port = 12347
        self.s.connect((host,port))
        self.text.insert(END,"Linked\n")
        t = threading.Thread(target=tcplink,args=(self.s,self.text))
        t.start()

def tcplink(sock,text):
    while True:
        text.insert(END,"[other's Message]"+sock.recv(1024).decode()+"\n")

ChatServer()

服务端:

import socket
import threading
import time

def tcplink(sock,addr):
    print("Accept new connection from %s:%s" % addr)
    sock.send("Welcome!".encode())
    while True:
        data = sock.recv(1024).decode()
        time.sleep(1)
        if data=='exit' or not data:
            break
        sock.send("Hellom%s!" %data.encode())
    sock.close()
    print("Connection from %s:%s closed"%addr)


host =socket.gethostname()
port = 12347
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(5)
while True:
    sock,addr = s.accept()
    t = threading.Thread(target=tcplink,args=(sock,addr))
    t.start()
Last modification:September 7th, 2018 at 08:23 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment