django实现websocket作为安卓开发后台(软件课设,oo聊天)

主要用到django,dwebsocket,mysql(这里给个大致流程,帮助有类似需要的同学指明方向)

没有想象的那么难,作为安卓端后台服务器,首先要搞明白干啥

1,建立连接,处理数据(其实就这俩,不需要推送网页啥的)
2,django自带的数据库使用的方法,只需要简单的修改settings即可连接mysql数据库。

下面详细的讲讲:

一、数据库

1,下载django和dwebsocket,注意python肯定是必要的。
2,下载mysql,初始化用户密码。(必要的,否则会有空密码情况,总是出错)
3,mysql中新建数据库,并在django中更改settings设置使用MySQL数据库。
4,在app中编写models.py并运行两条命令,与数据库同步

二、连接

4,与安卓客户端建立websocket连接,views.py中编辑函数建立连接即可,urls.py中就这一个函数就可以了)
5,不需要考虑并发,django本身具备的撑起来个软件课设还是可以的。
6,建立连接后注意保存标识每个连接,服务端发送信息要用(这块有点抽象,建立按连接返回的的websocket实际上包含了一系列信息,不用理解,整个字典,键值自己确定直接保存就行)

connections[ooID] = request.websocket #这样即可
settings.py代码粘贴可以看一下(具体的找视频学习)
"""
Django settings for server project.

Generated by 'django-admin startproject' using Django 2.0.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '2mrkz*)^j&k$n3ra9=rsz(vkl%&)&q0*m2z8@lkvt5@behs7vv'
import dwebsocket

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'serve'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
MIDDLEWARE_CLASSES=['dwebsocket.middleware.WebSocketMiddleware']

WEBSOCKET_ACCEPT_ALL=True  # 可以允许每一个单独的视图实用websockets

ROOT_URLCONF = 'server.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'server.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'user_name',
        'HOST': '127.0.0.1',
        'PORT': 3306,
        'USER': 'root',
        'PASSWORD': 'shamesha',
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'

views.py代码粘贴
from django.shortcuts import HttpResponse, render, redirect
from django.http import JsonResponse
from django.urls import path
from django.core import serializers
from .models import *
from builtins import str
import json
import os
# Create your views here.
# oo_num,password,登录变量
from dwebsocket.decorators import accept_websocket, require_websocket

connections = {}
little_num = 10000
little_group_num = 50000


@accept_websocket
def login(request):
    if request.is_websocket():

        title = request.GET.get('title')
        if title == "1":  # ............................................注册
            name = request.GET.get('name')
            pwd = request.GET.get('password')
            length = Users.objects.all().count()
            ooID = '%d'%(little_num + length) # 生成5位oo_num,根据用户数量递增
            ooID = str(ooID)
            print(name)
            if Users.objects.filter(sname=name).count():
                request.websocket.send(json.dumps({'error':"the name has been used by others ,you can change a name",'title':"19"}))
            else:
                users = Users(soo_num=ooID, sname=name, spwd=pwd)
                users.save()
                information = {
                    'ooID': ooID,
                    'name': name,
                    'password': pwd,
                    'title': "1",
                }
                request.websocket.send(json.dumps(information))
                while True:
                    j = 0
            # request.websocket.close()
        if title == "2":  # ...........................................登录
            pwd = request.GET.get('password')
            ooID = request.GET.get('ooID')
            # print(ooID, pwd)
            if (Users.objects.filter(soo_num=ooID, spwd=pwd).count()):  # 账号密码正确
                # print(ooID, type(ooID))
                connections[ooID] = request.websocket  # 根据登录信息存储socket
                #print(connections)
                name = Users.objects.get(soo_num=ooID, spwd=pwd).sname
                connections[ooID].send(json.dumps({'name': name, 'title': "20"}))  # 先发送用户昵称
                while True:
                    msg = request.websocket.wait()
                    print(type(msg), msg)
                    msg = json.loads(msg)
                    print(msg['title'])
                    print("out msg")
                    continue_connect(msg, ooID)  # .................进入持续连接状态
            else:  # ......................................................账号密码错误
                # print("prepare to error3 ")
                information = {
                    'error': "sorry,your oo_num or password is wrong",
                    'title': "19",
                }
                request.websocket.send(json.dumps(information))
                for i in range(10000):
                    j = 0
                request.websocket.close()
            # print("dsd3", title)


# @accept_websocket
def continue_connect(msg, hostnum):  # 处理各种请求根据文档。(request_websocket是主人用户的socket)
    if (msg['title'] == "3"):  # 客户端请求单聊历史记录,查询并发送(title=31是最后一个包)
        ooFriendID = msg['ID']  # 朋友账号
        ooID = msg['ooID']  # 客户端方账号
        oofriend_record = Information_save.objects.filter(soo_num=ooID, soofriend_num=ooFriendID)
        ooFriendName = Users.objects.get(soo_num=ooFriendID).sname
        for oofriend_temp in oofriend_record:  # 将好友列表发送出去
            title = "3"
            oofriend_information = {
                'ooFriendID': ooFriendID,
                'ooFriendName':ooFriendName,
                'type': oofriend_temp.soo_type,
                'message': oofriend_temp.soo_record,
                'title': title,
            }
            connections[hostnum].send(json.dumps(oofriend_information))
            
    elif msg['title'] == "4":  # 单聊,向好友发送消息。
        ooFriendID = msg['ID']
        ooID = msg['ooID']
        message = msg['message']
        print(type(msg), msg)
        #先将信息存入数据库中:
        record_save = Information_save(soo_num=ooID, soofriend_num=ooFriendID, soo_type=1, soo_record=message)
        record_save.save()
        record_save2 = Information_save(soo_num=ooFriendID, soofriend_num=ooID, soo_type=2, soo_record=message)
        record_save2.save()
        ooFriendName = Users.objects.get(soo_num=ooID).sname
        if (ooFriendID in connections):  # 如果好友在线
            news_information = {
                'ooID': ooFriendID,
                'ooFriendID': ooID,
                'ooFriendName':ooFriendName,
                'message': message,
                'title': "4",
            }
            connections[ooFriendID].send(json.dumps(news_information))

    elif msg['title'] == "5":  # 加好友
        ooFriendID = msg['ID']
        ooID = msg['ooID']
        # 检测是否已加好友
        if (User_friend.objects.filter(soo_num=ooID, soofriend_num=ooFriendID)):
            connections[hostnum].send(json.dumps({'error': "has been your friend"}))
        else:
            ooFriendName = Users.objects.get(soo_num=ooFriendID).sname
            name=Users.objects.get(soo_num=ooID).sname
            # 将好友关系信息存入User_friend
            friend = User_friend(soo_num=ooID, soofriend_num=ooFriendID, soofriend_name=ooFriendName)
            friend.save()
            friend = User_friend(soo_num=ooFriendID, soofriend_num=ooID, soofriend_name=name)
            friend.save()
            # 返回客户端信息
            information = {
                'ooFriendID': ooFriendID,
                'ooFriendName': ooFriendName,
                'title': "5",
            }
            connections[hostnum].send(json.dumps(information))

    elif msg['title'] == "6":  # 群注册
        length = Group_bulid.objects.all().count()
        groupID = '%d'%(little_group_num + length)  # 生成5位oo_num,根据用户数量递增
        #groupID = str(groupID)
        groupName = msg['groupName']
        ooID = msg['ooID']
        if (Group_bulid.objects.filter(sgroup_name=groupName, sgroup_hoster=ooID)):
            connections[hostnum].send(json.dumps({'error': "has been this group"}))
        else:
            groupbulid = Group_bulid(sgroup_num=groupID, sgroup_name=groupName, sgroup_hoster=ooID)  # 存入数据库
            groupbulid.save()
            name=Users.objects.get(soo_num=ooID).sname
            groupin = Group_in(sgroup_num=groupID, sgroup_name=groupName, soo_num=ooID,sname=name)
            groupin.save()
            information = {
                'groupID': groupID,
                'groupName': groupName,
                'title': "6",
            }
            connections[hostnum].send(json.dumps(information))

    elif msg['title'] == "8":  # 加群
        # 检查有没有群
        groupID = msg['ID']
        ooID = msg['ooID']
        name=Users.objects.get(soo_num=ooID).sname
        if (Group_bulid.objects.filter(sgroup_num=groupID)):
            if(Group_in.objects.filter(sgroup_num=groupID,soo_num=ooID).count()):
                connections[hostnum].send(json.dumps({"error":"you have been in this group ",'title':"81"}))
            else:
                groupName = Group_bulid.objects.get(sgroup_num=groupID).sgroup_name
                groupin = Group_in(sgroup_num=groupID, sgroup_name=groupName, soo_num=ooID,sname=name)
                groupin.save()
                information = {
                    'groupName': groupName,
                    'groupID': groupID,
                    'title': "8",
                }
                connections[hostnum].send(json.dumps(information))
        else:
            information = {
                'error': "this groupID has not been in server",
                'title': "81",
            }
            connections[hostnum].send(json.dumps(information))

    elif msg['title'] == "7":#(群聊)
        ooID = msg['ooID']
        groupID = msg['ID']
        message = msg['message']
        name = Users.objects.get(soo_num=ooID).sname
        # 存入群记录数据库:
        group_record = Group_record(sgroup_num=groupID, soo_num=ooID, soo_name=name, soo_record=message)
        group_record.save()
        # 获取群内成员ID:,在线的则发送
        group_members = Group_in.objects.filter(sgroup_num=groupID)
        ooFriendName = Users.objects.get(soo_num=ooID).sname
        information = {
            'ooFriendID': ooID,
            'ooFriendName':ooFriendName,
            'groupID': groupID,
            'message': message,
            'title': "7",
        }
        for group_member in group_members:
            ID = group_member.soo_num
            if ID in connections:
                connections[ID].send(json.dumps(information))

    elif msg['title'] == "9":#群聊历史纪录
        ooID = msg['ooID']
        groupID = msg['ID']#群号
        print("群聊历史纪录1")
        group_records = Group_record.objects.filter(sgroup_num=groupID)
        print("群聊历史纪录2",group_records.count())
        groupName=Group_bulid.objects.get(sgroup_num=groupID).sgroup_name
        for group_record in group_records:
            title = 9
            #if (group_record == group_records.last()):
            #    title = 91
            groupID = group_record.sgroup_num
            sendID = group_record.soo_num
            sendName = group_record.soo_name
            message = group_record.soo_record
            informations = {
                'groupID': groupID,
                'groupName':groupName,
                'sendID': sendID,
                'sendName': sendName,
                'message': message,
                'title': title,
            }
            print("群聊历史纪录")
            connections[hostnum].send(json.dumps(informations))

    elif msg['title'] == "10" or msg['title'] == "101" :#客户端发送文件
        if (msg['ooFriendID'] in connections) and msg['title'] == "101":  # 如果好友在线
            news_information = {
                'ooID': msg['ooFriendID'],
                'ooFriendID': msg['ooID'],
                'fileName':msg['fileName'],
                'title': msg['title'],
            }
            connections[msg['ooFriendID']].send(json.dumps(news_information))
        if msg['title'] == "101":
            files = File_record(soo_num=msg['ooID'], soofriend_num=msg['ooFriendID'], soo_type="1", soo_filename=msg['fileName'])
            files.save()
            files = File_record(soo_num=msg['ooFriendID'], soofriend_num=msg['ooID'], soo_type="2", soo_filename=msg['fileName'])
            files.save()
            record_save = Information_save(soo_num=msg['ooID'], soofriend_num=msg['ooFriendID'], soo_type="3", soo_record=msg['fileName'])
            record_save.save()
            record_save2 = Information_save(soo_num=msg['ooFriendID'], soofriend_num=msg['ooID'], soo_type="3", soo_record=msg['fileName'])
            record_save2.save()
        file = open(msg['fileName'], mode='a+')
        #for message in msg['message']:
        file.write(msg['message'])
        file.close()

    elif msg['title'] == "11":#获取文件记录
        files = File_record.objects.filter(soofriend_num=msg['ooFriendID'], soo_num=msg['ooID'])
        for file in files:
            title="11"
            if file==files.last():
                title="111"
            information={
                'ooID': file.soo_num,
                'ooFriendID': file.soofriend_num,
                'fileName': file.soo_filename,
                'type':file.soo_type,
                'title': title,
            }
            connections[hostnum].send(json.dumps(information))

    elif msg['title'] == "12":#获取群列表
        ooID=msg['ooID']
        group_information_all = Group_in.objects.filter(soo_num=ooID)
        for group_temp in group_information_all:
            title = "12"
            #if(group_temp == group_information_all.last()):
            #    title = "121"
            group_informations={
                'groupName':group_temp.sgroup_name,
                'groupID':group_temp.sgroup_num,
                'title':title,
            }
            connections[hostnum].send(json.dumps(group_informations))

    elif msg['title'] == '13':#群内好友列表
        host=Group_bulid.objects.get(sgroup_num=msg['ID'])
        groupHoster=host.sgroup_hoster
        groupHosterName=Users.objects.get(soo_num=groupHoster).sname
        groups=Group_in.objects.filter(sgroup_num=msg['ID'])
        groupUsers=" "
        for group in groups:
            groupUsers=groupUsers+group.sname
            groupUsers=groupUsers+"\n"
        information={
            'groupID':msg['ID'],
            'message':groupUsers,
            'title':"131",
        }
        connections[hostnum].send(json.dumps(information))

    elif msg['title'] == "14":#获取文件
        file = open(msg['fileName'], mode='r')
        message = file.read()
        title="141"
        information={
            'fileName':msg['fileName'],
            'message':message,
            'title':title
            }
        connections[hostnum].send(json.dumps(information))

    elif msg['title'] == '21':#客户端主动获取好友列表
        oofriend_information_all = User_friend.objects.filter(soo_num=msg['ooID'])
        for oofriend_temp in oofriend_information_all:  # 将好友列表发送出去
            title = "21"
            #if (oofriend_temp == oofriend_information_all.last()):
             #   title = "210"
            # print(oofriend_temp.soofriend_num)
            oofriend_information = {
                'ooFriendID': oofriend_temp.soofriend_num,
                'ooFriendName': oofriend_temp.soofriend_name,
                'title': title
            }
            connections[hostnum].send(json.dumps(oofriend_information))

    elif msg['title'] == '66':
        groupName=Group_bulid.objects.get(sgroup_num=msg['groupID']).sgroup_name
        name=Users.objects.get(soo_num=msg['ooFriendID']).sname
        if(Group_in.objects.filter(sgroup_num=msg['groupID'],soo_num=msg['ooFriendID'])):
            connections[hostnum].send(json.dumps({"error":"the boy  have been in this group ",'title':"81"}))
        else:
            groupin = Group_in(sgroup_num=msg['groupID'], sgroup_name=groupName, soo_num=msg['ooFriendID'],sname=name)
            groupin.save()
            connections[hostnum].send(json.dumps({'answer':"ok",'title':"66"}))
    
    

    elif msg['title'] == '404':#客户端即将中断
        connections.pop(msg['ooID'])


在app里面写哦,搞懂Django的基本结构再来看哦

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值