主要用到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 = TrueALLOWED_HOSTS = ['*']# Application definitionINSTALLED_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  # 可以允许每一个单独的视图实用websocketsROOT_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/#databasesDATABASES = {'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-validatorsAUTH_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 = TrueUSE_L10N = TrueUSE_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_websocketconnections = {}
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).snameconnections[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 = 0request.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).snamefor 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).snameif (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).snamename=Users.objects.get(soo_num=ooID).sname# 将好友关系信息存入User_friendfriend = 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).snamegroupin = 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).snameif (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_namegroupin = 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).snameinformation = {'ooFriendID': ooID,'ooFriendName':ooFriendName,'groupID': groupID,'message': message,'title': "7",}for group_member in group_members:ID = group_member.soo_numif 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_namefor group_record in group_records:title = 9#if (group_record == group_records.last()):#    title = 91groupID = group_record.sgroup_numsendID = group_record.soo_numsendName = group_record.soo_namemessage = group_record.soo_recordinformations = {'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_hostergroupHosterName=Users.objects.get(soo_num=groupHoster).snamegroups=Group_in.objects.filter(sgroup_num=msg['ID'])groupUsers=" "for group in groups:groupUsers=groupUsers+group.snamegroupUsers=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_namename=Users.objects.get(soo_num=msg['ooFriendID']).snameif(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的基本结构再来看哦

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

  1. 安卓开发常用软件及环境配置

    安卓开发常用软件及环境配置 修改文件权限 chmod u=rwx,g=r,o=r file.txt 安卓studio代理配置 systemProp.http.proxyHost=127.0.0.1 s ...

  2. 基于ZigBee+ESP32+MQTT+EMQX+TomCat+Servlet接口+MySQL+安卓app的物联网课设

    文章目录 一.写在前面 二.课设简介 三.不眠夜开始了 1.基于zigbee网络数据采集的底层实现 2.基于ESP32和mqtt协议的数据上传功能 3.使用EMQX作为MQTT服务器软件 4.使用Ja ...

  3. android 安卓开发相关软件下载神地址

    http://www.androiddevtools.cn/ 官方地址  www.androiddevtools.cn AndroidDevTools简介 Android Dev Tools官网地址: ...

  4. java安卓开发模板软件_用Java模板创建你的Hello, Harmony!

    2020年度华为开发者大会"HDC Together"于9月10日至9月12日在东莞松山湖成功举办.作为一名开发者,我有幸参加这一年一度的盛会,并且亲身体验了 Harmony OS ...

  5. (附源码)SSM医疗机构药房管理系统软件开发-后台软件设计与实现JAVA计算机毕业设计项目

    项目运行 环境配置: Jdk1.8 + Tomcat7.0 + Mysql + HBuilderX(Webstorm也行)+ Eclispe(IntelliJ IDEA,Eclispe,MyEclis ...

  6. 安卓开发——锁定软件——输入密码后重复弹出输入密码窗口的解决方法

    在判断输入的密码正确后,发送一个广播 //进行输入密码的验证if(new MD5Utils().digestPassWord(_intput_password).equals(password)){/ ...

  7. 安卓开发设置软件媒体声音

    需要先保存系统声音并且获取最大声音,然后设置系统声音最大再使用 mediaPlayer.setVolume(volumeNum,volumeNum); 去设置播放声音,播放完成后把系统声音设置成之前保 ...

  8. 从事安卓开发6年,我都有哪些收获?

    作者 | 拭心 来源 | 拭心又在思考了我的天(ID:evolution1024) 一转眼,我从事安卓开发工作已经六年有余,对安卓开发甚至软件开发的价值,每年都有更进一步的认识.对未来的方向,也从刚入 ...

  9. 六年安卓开发的技术回顾和展望

    大家好,我是 shixin. 一转眼,我从事安卓开发工作已经六年有余,对安卓开发甚至软件开发的价值,每年都有更进一步的认识.对未来的方向,也从刚入行的迷茫到现在逐渐清晰.我想是时候做一个回顾和展望了. ...

最新文章

  1. WordPress Editorial Calendar插件权限安全绕过漏洞
  2. 64岁Python之父退休失败,正式加入微软搞开源
  3. 软件工程(2018)第1次团队作业
  4. android(cm11)状态栏源码分析(一)
  5. convert.todatetime指定日期格式_SQL基础知识V2——常用日期函数
  6. 正则表达式:日期格式的校验(日期+时间)
  7. 【机器学习】机器学习从零到掌握之二 -- 教你实现K近邻算法
  8. 2 亚马逊_索泰称仅亚马逊渠道就收到2万块RTX 3080显卡订单,无法按时发货
  9. 前端 鼠标一次移动半个像素_今天来说说鼠标的DPI该怎么设置
  10. shell脚本基础练习题
  11. 为国内软件质量呐喊:《2021年国内质量调查报告》发布
  12. 浅谈大型互联网的企业入/侵及防护策略
  13. linux mips架构PHYS_OFFSET、CAC_BASE、HIGHMEM_START、PAGE_OFFSET、virt_to_phys、phys_to_virt、page_to_phys的定义
  14. 今日分享-ios蓝牙
  15. 基础的sql语句练习题+答案
  16. 使用DHCP动态管理主机地址
  17. 学习笔记(11):OmniPlan项目管理就该这样学-拆分任务
  18. 从Foxmail向Thunderbird(TB)导出邮件
  19. 深圳是“物联网之城”|草根逆袭之地
  20. 用Python分析韩国女团喜欢什么单词 !

热门文章

  1. [情侣空间] 基于spring boot的自制情侣空间
  2. 百度连续四年亮相全球量子信息处理顶会QIP 宣布量子战略规划升级
  3. 分享一款基于aui框架的图文发布界面
  4. c语言 r语言 java,R语言rJava包安装载入及JAVA环境配置
  5. 基于I2C/SPI总线的温湿度采集与OLED显示
  6. vue计算本周是今年的第几周
  7. 巴比特 | 元宇宙每日必读:入职三个月就遭遣散,热潮过后的元宇宙会走向哪里?...
  8. 青鸟s1java云题库答案_北大青鸟S1java内部测试试卷(试题)
  9. Android开发通知栏的那些事
  10. Codeforces Round #727 (Div. 2)