计算机网络Python_socket聊天室

前言

计算机网络小课程设计简单记录,大佬轻点喷,菜哭了
环境:python3

基于tcp

service端

import socket
import threading
con = threading.Condition()
host = '0.0.0.0'
port = int(input('请输入服务端口:'))
#print(type(port))
s = socket.socket()
s.bind((host, port))
s.listen(1)
print("监听开始")
data = ""
def NotifyAll(socket):
    global data
    if con.acquire(): #获取锁
        data = socket.encode('utf-8')
        con.notify_all() #表示当线程放弃对资源占用 通知其他可以执行
        con.release()      #释放锁
def threadOut(conn, content):        #发送消息
    global data
    while True:
        if con.acquire():
            con.wait()  #放弃资源占用
            if data:
                try:
                    #print(data)
                    conn.send(data)
                    con.release() #解锁
                except:
                    con.release()
                    return
def threadIn(conn, content):  #接收消息
    global data
    while True:
        try:
            temp = conn.recv(1024).decode('utf-8')
            #print(type(temp))
            if not temp:
                conn.close()
                return
            if temp == 'exit':
                conn.s

            NotifyAll(temp)
            print(data)
        except:
            temp = content +':exit'
            NotifyAll(temp.decode('utf-8'))
           # print(error)
while True:
    conn,address = s.accept()   #返回的是元组
    print("连接者:"+str(address[0])+':'+str(address[1]))
    content = conn.recv(1024).decode('utf-8') #传入的姓名
    NotifyAll("欢迎"+content+"加入聊天室")
    #print(data)
    conn.send(data)
    threading.Thread(target=threadOut, args=(conn, content)).start()
    threading.Thread(target=threadIn, args=(conn, content)).start()

client端

import socket
import threading
people_name = ''
people_send = ''

def client_send(sock):
    global people_name
    global people_send
    while True:
        people_send = input() #接收输入
        people_send = people_name + ':' + people_send
        sock.send(people_send.encode('utf-8'))
        if 'exit' in people_send:
            sock.shutdown(2)
            sock.close()
            break

def client_accept(sock):
    global people_send
    while True:
        try:
            accept = sock.recv(1024).decode('utf-8') #一次接收数据1024
            #print(type(accept))
            if not accept:
                break
            if accept != people_send:
                print(accept)
        except:
            print("error")
            break
people_name = input('输入你的名字:')
service_ip = input('输入你要连接的ip地址:')
service_port = int(input('输入你要连接的端口:'))
sock = socket.socket() #创建socket对象
sock.connect((service_ip, service_port))    #address的格式为元组(hostname,port)
sock.send(people_name.encode('utf-8'))
th_send = threading.Thread(target=client_send, args=[(sock)]) #发送消息线程
th_send.start() #启动线程
th_accept = threading.Thread(target=client_accept, args=[(sock)]) #发送消息线程
th_accept.start() #启动线程

大致效果图


基于udp

service端

import socket
import threading
def service_send(s):
    global data
    global address
    while True:
        try:
            print(address)
            data, address_tmp = s.recvfrom(1024)
            if address_tmp not in address: # 不在用户中
                # 将用户传入聊天室广发给用户
                address[address_tmp] = data.decode('utf-8')
                data = data.decode('utf-8') + "加入聊天室"
                for add in address:
                    print(data)
                    s.sendto(data.encode('utf-8'), add)
                continue
            # 用户退出
            if 'exit' in data.decode('utf-8'):
                name = address[address_tmp]
                del address[address_tmp]
                s.sendto((name + "你已经退出成功").encode('utf-8'), address_tmp)
                print(address)
                for user_addr in address:
                    s.sendto((name + "退出聊天室").encode('utf-8'), user_addr)
            else:
                data = data.decode('utf-8')
                # s.sendto(("发送成功").encode('utf-8'), address_tmp)
                for user_addr in address:
                    if user_addr != address_tmp:
                        s.sendto(data.encode('utf-8'), user_addr)
                s.sendto(("发送成功").encode('utf-8'), address_tmp)
        except:
            print("error")

if __name__ == '__main__':
    con = threading.Condition()
    host = '0.0.0.0'
    port = int(input('请输入服务端口:'))
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # 创建socket对象
    service_addr = (host, port)
    s.bind(service_addr)  # 绑定地址和端口
    print("监听开始")
    data = ""
    address = {}  # 字典存储用户地址{(addr:name)}
    service_send(s)
# threading.Thread(target=threadOut, args=(conn, content)).start()
# threading.Thread(target=threadIn, args=(conn, content)).start()

client端

import socket
import threading
people_name = ''
people_send = ''

def client_send(sock):
    global people_name
    global people_send
    global address
    while True:
        people_send = input() # 接收输入
        people_send = people_name + ':' + people_send
        sock.sendto(people_send.encode('utf-8'), address)
def client_accept(sock):
    global people_send
    while True:
        try:
            accept, accept_address = sock.recvfrom(1024) # 一次接收数据1024
            # print(type(accept))
            accept = accept.decode('utf-8')
            if not accept:
                break
            if accept != people_send:
                print(accept)
        except:
            print("error")
            break
people_name = input('输入你的名字:')
service_ip = input('输入你要连接的ip地址:')
service_port = int(input('输入你要连接的端口:'))
address = (service_ip, service_port)
# print(address)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # 创建socket对象
# sock.connect((service_ip, service_port))    #address的格式为元组(hostname,port)
sock.sendto(people_name.encode('utf-8'), address)
th_send = threading.Thread(target=client_send, args=[(sock)]) #发送消息线程
th_send.start()  # 启动线程
th_accept = threading.Thread(target=client_accept, args=[(sock)]) #发送消息线程
th_accept.start()  # 启动线程

大致效果图


posted @ 2021-05-31 21:27  Lmg66  阅读(202)  评论(1编辑  收藏  举报