zoukankan      html  css  js  c++  java
  • 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()

    """

  • 相关阅读:
    IP地址与域名的关系
    微信公众平台开发
    jquery实现对div的拖拽功能
    js控制表格实时编辑
    删除提示框插件
    基于jquery的bootstrap在线文本编辑器插件Summernote (转)
    从输入网址到显示网页的过程中发生了什么?
    TP框架---thinkphp中ajax分页
    使背景图片适应不同分辨率电脑
    TP框架---验证码
  • 原文地址:https://www.cnblogs.com/chenfei2928/p/12868893.html
Copyright © 2011-2022 走看看