用python实现一个简单的聊天功能,tcp,udp,socketserver版本

基于tcp协议版本

服务器端

import socket

server = socket.socket()
server.bind(('127.0.0.1', 8001))
server.listen(5)

flag = 1
while flag:
    conn, addr = server.accept()

    while 1:
        send_msg = input('msg:').strip().lower()
        conn.send(send_msg.encode())
        if send_msg == 'q':
            flag = 0
            break
        msg = conn.recv(1024).decode()
        if msg == 'q': break
        print(msg)
    print('当前客户端断开连接等待新的连接')
    cmd = input('输入(q)退出,其他返回聊天:').strip().lower()
    if cmd == 'q':
        flag = 0
    conn.close()

server.close()

 

客户端

import socket

client = socket.socket()
client.connect(('127.0.0.1', 8001))
while 1:
    # client.send(b'byebye')
    msg = client.recv(1024).decode().lower()
    print(msg)
    if msg == 'q': break
    send_msg = input('msg:').lower().strip()
    client.send(send_msg.encode())
    if send_msg == 'q': break


client.close()

 

基于tcp协议socketserver版本

服务器端

import socketserver


class Myserver(socketserver.BaseRequestHandler):
    def handle(self):
        conn = self.request     # 相当于conn = server.accept()
        while True:

            msg = conn.recv(1024).decode()
            print(msg)
            content = input('>>>>')
            conn.send(content.encode())


server = socketserver.ThreadingTCPServer(('127.0.0.1', 8001), Myserver)

server.serve_forever()

 

客户端

import socket

client = socket.socket()

client.connect(('127.0.0.1', 8001))

while True:
    content = input('>>>>')
    client.send(content.encode())
    msg = client.recv(1024).decode()
    print(msg)

client.close()

 

基于udp协议版本

服务器端

import socket

server = socket.socket(type=socket.SOCK_DGRAM)
server.bind(('127.0.0.1', 9000))
while True:
    msg, clt_addr = server.recvfrom(1024)
    print(msg.decode())
    content = input('>>>')
    server.sendto(content.encode(), clt_addr)

sk.close()

 

客户端

import socket

client = socket.socket(type=socket.SOCK_DGRAM)

count = 0
while True:
    count += 1
    content = input('>>>')
    content = '%s : %s' % (count, content)
    client.sendto(content.encode(), ('127.0.0.1', 9000))
    msg, addr = client.recvfrom(1024)
    print(msg.decode())

sk.close()

 

posted @ 2019-01-25 10:06  平平无奇小辣鸡  阅读(743)  评论(0编辑  收藏  举报