• Python网络编程socket 简易聊天窗


    server端
    """
    import socket
    import tkinter as tk
    from threading import Thread

    sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sk.bind(("127.0.0.1",10010))
    sk.listen()

    准备接受连接

    print('准备完毕----------')
    conn,address = sk.accept()
    print('客户端连接成功')

    创建窗口

    win = tk.Tk()
    win.title('聊天窗口')
    win.geometry('500x300')

    msg_box = tk.Text(win) #文本域

    var = tk.Variable()
    tf = tk.Entry(win,textvariable=var) # 用户输入文本框

    简单布局

    msg_box.pack(side = tk.TOP,fill=tk.X)
    tf.pack(side=tk.BOTTOM,fill=tk.X)

    def func(event):
    s = var.get()
    conn.send(s.encode("utf-8"))
    print(s)
    var.set("")

    tf.bind("", func)

    def recv():
    while 1:
    msg_bytes = conn.recv(1024)
    s = msg_bytes.decode('utf-8')
    msg_box.insert(tk.END, s+" ")

    t = Thread(target=recv)
    t.start()

    win.mainloop()

    conn.close()
    sk.close()
    """

    client端

    """
    import socket
    import tkinter as tk
    from threading import Thread

    sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    print('准备连接服务器')
    sk.connect(("127.0.0.1",10010))
    print('连接成功')

    创建窗口

    win = tk.Tk()
    win.title('聊天窗口222')
    win.geometry('500x300')

    msg_box = tk.Text(win) #文本域

    var = tk.Variable()
    tf = tk.Entry(win,textvariable=var) # 用户输入文本框

    简单布局

    msg_box.pack(side = tk.TOP,fill=tk.X)
    tf.pack(side=tk.BOTTOM,fill=tk.X)

    def func(event):
    s = var.get()
    sk.send(s.encode("utf-8"))
    print(s)
    var.set("")

    tf.bind("", func)

    def recv():
    while 1:
    msg_bytes = sk.recv(1024)
    s = msg_bytes.decode('utf-8')
    msg_box.insert(tk.END, s+" ")

    t = Thread(target=recv)
    t.start()

    win.mainloop()

    sk.close()

    """

  • 相关阅读:
    606. Construct String from Binary Tree
    696. Count Binary Substrings
    POJ 3255 Roadblocks (次短路)
    POJ 2823 Sliding Window (单调队列)
    POJ 1704 Georgia and Bob (博弈)
    UVa 1663 Purifying Machine (二分匹配)
    UVa 10801 Lift Hopping (Dijkstra)
    POJ 3281 Dining (网络流之最大流)
    UVa 11100 The Trip, 2007 (题意+贪心)
    UVaLive 4254 Processor (二分+优先队列)
  • 原文地址:https://www.cnblogs.com/chenfei2928/p/12868893.html
Copyright © 2020-2023  润新知