Python程序设计之网络编程(4)

1.基于TCP实现聊天小程序

①截图
Python程序设计之网络编程(4)_第1张图片
②代码分析
a)发送端代码

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind((HOST1, P))
            s.listen(1)
            conn, addr = s.accept()
            print('Connect by:', addr)
            c=entry.get()
            conn.sendall(str(c).encode())
            conn.close()
        except Exception as e:
            print("Deliver eroor!")
        finally:
            s.close()

b)接收端代码

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind((HOST1, P))
            s.listen(1)
            conn, addr = s.accept()
            print('Connect by:', addr)
            c=entry.get()
            conn.sendall(str(c).encode())
            conn.close()
        except Exception as e:
            print("Deliver eroor!")
        finally:
            s.close()

c)GUI代码

    myTk=tkinter.Tk()
    myTk["width"]=300
    myTk["height"]=500
    myTk.title("Clint")
    #初始化指定回复消息内容
    #message=[]
    #初始化接收信息内容
    #feedback=[]
    m=tkinter.StringVar(value='')
    f=tkinter.StringVar(value='')
    #添加布局
    label=tkinter.Label(myTk,text="Message:",width=60)
    label.place(x=10,y=30,width=60,height=20)
    entry=tkinter.Entry(myTk,textvariable=m)
    entry.place(x=100,y=30,width=100,height=20)

    label1=tkinter.Label(myTk,text="FeedBack",width=60)
    label1.place(x=10,y=70,width=60,height=20)
    entry1=tkinter.Entry(myTk,textvariable=f)
    entry1.place(x=100,y=70,width=100,height=20)

    listbox=tkinter.Listbox(myTk)
    listbox.place(x=30,y=200,width=240,height=200)
学习笔记

1.UDP和TCP聊天实现的异同(UDP实现聊天参看文章:https://blog.csdn.net/qxyloveyy/article/details/104977360)
a)相同部分
初始化套接字:

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

接收数据(需要解码)和发送的数据(需要编码):

data = data.decode()
data1=str(c).encode()

b)不同部分
①接收方式
UDP接收

        s.bind(('', 5001))#接收端连接
        data, addr = s.recvfrom(1024)#接收数据
        #s1.set(addr[0])
        s2.set(data.decode())
        messageList.insert(0, 'message:' + s2.get())

TCP接收

            s.connect((HOST1, P))#接收端的连接
            data = s.recv(1024)#接收数据
            data = data.decode()
            listbox.insert(0, data)

②发送方式
UDP发送消息

        s.sendto(str(s1).encode(), (主机IP, 端口号))#发送小徐

TCP发送消息

            s.bind((HOST, PORT))	#建立连接
            s.listen(1)#监听
            conn, addr = s.accept()#接收数据
            print('Connect by:', addr)
            c=entry.get()
            conn.sendall(str(c).encode())
            conn.close()

2.使用异常机制来使得连接最后一定会被关闭

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind((HOST, PORT))
            s.listen(1)
            conn, addr = s.accept()
            print('Connect by:', addr)
            c=entry.get()
            conn.sendall(str(c).encode())
            conn.close()
        except Exception as e:
            print("Deliver eroor!")
        finally:
            s.close()

你可能感兴趣的:(Python,program,design)