俺是菜鸟,俺想做一个俺android的登陆注册功能,利用socket通信,数据库是mysql。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了俺是菜鸟,俺想做一个俺android的登陆注册功能,利用socket通信,数据库是mysql。相关的知识,希望对你有一定的参考价值。

俺是菜鸟,俺想做一个俺android的登陆注册功能,利用socket通信,数据库是mysql。我的思路是:模拟器是客户端,主机是服务器端。数据库在服务器端,当输入账号和密码,点击登陆按钮时,通过socket利用指定端口号访问服务器端,服务器端用通过db类来访问相应的数据库中的表,将数据库数据和输入的数据进行比较,如果一致就返回一个true给客户端,客户端之前规定如果返回true就t跳转到主界面,出现toase登陆成功,反之如果返回false就出现toase提示失败。具体代码的不知道怎么实现。。。各位好心的大侠们帮帮偶吧~~~~><~~~~~~~急用啊。。。。。。。。。

给段用xml传输的代码你看看吧。
客户端
package com.example.xword;
import java.io.BufferedInputStream;import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.util.ByteArrayBuffer;import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.data.User;
import android.os.AsyncTask;import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class UserLoginActivity extends Activity
EditText uname; EditText upass;
Button loginbut;
User user;

@Override public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);

uname = (EditText) findViewById(R.id.uname); upass = (EditText) findViewById(R.id.password);
loginbut = (Button) findViewById(R.id.loginbut);

loginbut.setOnClickListener(new View.OnClickListener()
public void onClick(View v) // TODO Auto-generated method stub
String username = uname.getText().toString();
String userpass = upass.getText().toString();
// Toast.makeText(UserLoginActivity.this, "��ϲ",
// Toast.LENGTH_LONG).show();
LoginTask task = new LoginTask();
task.execute(username, userpass);


);

public class LoginTask extends AsyncTask<String, Integer, String>
@Override protected String doInBackground(String... params)
// TODO Auto-generated method stub

StringBuffer sbuf = new StringBuffer(); sbuf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sbuf.append("<ulogin>\n");
sbuf.append("<username>" + params[0] + "</username>\n");
sbuf.append("<password>" + params[1] + "</password>");
// sbuf.append("<image>"+imgString+"</image>");

sbuf.append("</ulogin>");
String dataString = sbuf.toString();
try
URL url = new URL( "http://10.0.2.2:8080/androidserver/userlogin");
HttpURLConnection con = (HttpURLConnection) url
.openConnection();

con.setDoOutput(true); OutputStream os = con.getOutputStream();
os.write(dataString.getBytes());

int code = con.getResponseCode();
if (HttpURLConnection.HTTP_OK == code)
// byte buf[]=new byte[1024]; InputStream is = con.getInputStream();
// int c=is.read(buf, 0, buf.length);

// String result=new String(buf,0,c);
System.out.println("0"); DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
try
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(is);
// root <university>
// Element root = doc.getDocumentElement();
// System.err.println(root.getAttribute("name"));
// all college node
NodeList info = doc.getElementsByTagName("userid");

Node node = info.item(0); String nodeValue = node.getTextContent();

if (info == null)
return "LOGINFAIL";

if ("fail".equals(nodeValue))
return "LOGINFAIL";
else user.setUser_id(Integer.parseInt(nodeValue));
return "LOGINSUCCESS";


catch (Exception e) e.printStackTrace();
return "LOGINFAIL";


// //////////////////////////////////////////
else return "LOGINFAIL";


catch (Exception ex) ex.printStackTrace();
return "LOGINFAIL";



@Override protected void onPostExecute(String result)
// TODO Auto-generated method stub
super.onPostExecute(result);
if ("LOGINSUCCESS".equals(result))

Toast.makeText(UserLoginActivity.this, "登陆成功", Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.setClass(UserLoginActivity.this, MainActivity.class);
startActivity(intent);
UserLoginActivity.this.finish();

else if ("LOGINFAIL".equals(result))
Toast.makeText(UserLoginActivity.this, "登录失败,请检查用户名密码", Toast.LENGTH_LONG).show();




@Override public boolean onCreateOptionsMenu(Menu menu)
getMenuInflater().inflate(R.menu.activity_user_login, menu);
return true;




服务器端(servlet)
package com.main;
import java.io.ByteArrayInputStream;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.w3c.dom.Document;import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet
private static final long serialVersionUID = 1L;

/** * @see HttpServlet#HttpServlet()
*/
public LoginServlet()
super();
// TODO Auto-generated constructor stub


/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
// TODO Auto-generated method stub

doPost(request, response);

public class XMLHandler extends DefaultHandler String username = "";
String password = "";
// String image="";

StringBuffer temp = new StringBuffer();;
@Override public void characters(char[] ch, int start, int length)
throws SAXException
// TODO Auto-generated method stub
temp.append(new String(ch, start, length));


@Override public void endElement(String uri, String localName, String qName)
throws SAXException
// TODO Auto-generated method stub
// super.endElement(uri, localName, qName);

if ("username".equals(qName))
username = temp.toString(); else if ("password".equals(qName))
password = temp.toString();
// else if("image".equals(qName)) // image=temp.toString();
//


@Override public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
// TODO Auto-generated method stub
super.startElement(uri, localName, qName, attributes);
temp = new StringBuffer();



/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
// TODO Auto-generated method stub

String username = ""; String password = "";
XMLReader reader = null; try
reader = SAXParserFactory.newInstance().newSAXParser()
.getXMLReader();

XMLHandler handler = new XMLHandler(); reader.setContentHandler(handler);
reader.parse(new InputSource(request.getInputStream()));
// System.out.println(handler.image);
// BASE64Decoder decoder=new BASE64Decoder();
// byte[] imgbuffer=decoder.decodeBuffer(handler.image);
// ByteArrayInputStream bais=new ByteArrayInputStream(imgbuffer); // String path=request.getRealPath("/upload");
// System.out.println(path); // FileOutputStream fos=new FileOutputStream(path+"/upload.png");
// byte[] buf=new byte[1024];
// int c=0;
// while((c=bais.read(buf, 0, buf.length))!=-1)
// fos.write(buf,0,c);

//
// fos.close(); // bais.close();
//PrintWriter out = response.getWriter();
try Class.forName("com.mysql.jdbc.Driver"); // 加载驱动
// Class.forName("org.gjt.mm.mysql.Driver");
System.out.println("Success loading Mysql Driver!");
catch (Exception e)
System.out.print("Error loading Mysql Driver!");
e.printStackTrace();

try
Connection connect = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/xword", "root", "123456");
//填写数据库用户名密码等
System.out.println("Success connect Mysql server!");
Statement stmt = connect.createStatement();
System.out.println("Step0");
// ResultSet rs = stmt.executeQuery("select * from user");
String sqlstr;
ResultSet rs1;
sqlstr = "select*from user where(user_name='" + handler.username
+ "'and user_password='" + handler.password + "')";
rs1 = stmt.executeQuery(sqlstr);
System.out.println("Step1");
StringBuffer sbuf=new StringBuffer();
sbuf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sbuf.append("<ulogin>\n");
if (rs1.next())

sbuf.append("<userid>"+rs1.getInt(1)+"</userid>");


else

sbuf.append("<userid>fail</userid>");


sbuf.append("</ulogin>");
String dataString=sbuf.toString();
System.out.println("sbuf=" + sbuf);
response.getOutputStream().write(dataString.getBytes());
connect.close();
catch (Exception e)
// out.print("FAIL");
System.out.println("stepfail");
e.printStackTrace();


catch (Exception e) e.printStackTrace();


追问

我要的是socket通信的,不是http啊

追答

把http那一块换成socket不就可以了吗?具体可以查一查socket怎么用,然后按照这个结构写就行了

参考技术A 这个真心不建议你用原生的java语言开发,非常建议你用html5来进行,服务器上装php,然后软件端嵌入的html页面向服务器的php页面提交,软件端的html页面的javascript对返回的数据进行判断然后跳转页面就可以了。追问

俺已经做到一半了。。。。

追答

这东东最麻烦的就是服务器端的开发,你既然用了java开发,那么就尽快放弃用socket,改成用php做服务器端,然后返回一个xml文件作为验证结果。java读取xml就知道验证结果了。

本回答被提问者采纳
参考技术B 你学过了Android吗 呵呵!如果有点基础很好实现,我有代码,不知道怎么给你

微信小程序登陆注册功能实现

一、前言

我们在开发小程序时,经常会用到登陆注册功能。小程序有为我们提供用户授权登陆的功能,但是这个功能只能获取用户的头像和昵称,我们通常需要的是实现小程序账号密码的注册和登陆,本文是一个简单的小程序登陆注册功能的开发。
我们实现的功能有
1. 账号密码登陆
2.账号密码注册
3.退出登陆

二、原理讲解

因为我们账号密码的注册,就是把用户设置的账号密码存到数据库里,登陆也是从数据库里取账号和密码来校验。所以我们必须要有数据库。如果用传统的数据库来做,比较麻烦,所以我们今天就借助小程序云开发数据库来做。

三、代码实现

  1. 在app.js里初始化云开发环境id
    在这里插入图片描述

  2. 设置用户存储用户的数据库
    在云开发管理后台,点击数据库,然后点击 + 号,添加user数据表,如下图
    在这里插入图片描述

  3. 编写注册代码
    (1)注册页面的wxml文件

<!--index.wxml-->
输入用户名
<input class="input" bindinput="getName"></input>
输入用户账号
<input class="input" bindinput="getZhangHao"></input>
输入密码
<input class="input" bindinput="getMiMa"></input>
<button bindtap="zhuce" type="primary">注册</button>

(2)注册页面的js逻辑文件

Page({
  data: {
  name: '',
  zhanghao: '',
  mima: ''
  },
  //获取用户名
  getName(event) {
  console.log('获取输入的用户名', event.detail.value)
  this.setData({
   name: event.detail.value
  })
  },
  //获取用户账号
  getZhangHao(event) {
  console.log('获取输入的账号', event.detail.value)
  this.setData({
   zhanghao: event.detail.value
  })
  },
  // 获取密码
  getMiMa(event) {
  console.log('获取输入的密码', event.detail.value)
  this.setData({
   mima: event.detail.value
  })
  },
  
  //注册
  zhuce() {
  let name = this.data.name
  let zhanghao = this.data.zhanghao
  let mima = this.data.mima
  console.log("点击了注册")
  console.log("name", name)
  console.log("zhanghao", zhanghao)
  console.log("mima", mima)
  //校验用户名
  if (name.length < 2) {
   wx.showToast({
    icon: 'none',
    title: '用户名至少2位',
   })
   return
  }
  if (name.length > 10) {
   wx.showToast({
    icon: 'none',
    title: '用户名最多10位',
   })
   return
  }
  //校验账号
  if (zhanghao.length < 4) {
   wx.showToast({
    icon: 'none',
    title: '账号至少4位',
   })
   return
  }
  //校验密码
  if (mima.length < 4) {
   wx.showToast({
    icon: 'none',
    title: '密码至少4位',
   })
   return
  }
  //注册功能的实现
  wx.cloud.database().collection('user').add({
   data: {
    name: name,
    zhanghao: zhanghao,
    mima: mima
   },
   success(res) {
    console.log('注册成功', res)
    wx.showToast({
     title: '注册成功',
    })
    wx.navigateTo({
     url: '../login/login',
    })
   },
   fail(res) {
    console.log('注册失败', res)
   }
  })
  }
  })```
  (3)实现效果
  ![在这里插入图片描述](https://img-blog.csdnimg.cn/20210714141720707.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mjc3NTMwNA==,size_16,color_FFFFFF,t_70)

 4. 编写登录代码
(1)登录页面的wxml文件

```bash
<!--pages/login/login.wxml-->
输入账号
<input class="input" bindinput="getZhanghao"></input>
输入密码
<input class="input" bindinput="getMima"></input>
<button bindtap="login" type="primary">登录</button>

(2)登录页面的js逻辑文件

// pages/login/login.js
Page({
  data: {
  zhanghao: '',
  mima: ''
  },
  //获取输入的账号
  getZhanghao(event) {
  //console.log('账号', event.detail.value)
  this.setData({
   zhanghao: event.detail.value
  })
  
  },
  //获取输入的密码
  getMima(event) {
  // console.log('密码', event.detail.value)
  this.setData({
   mima: event.detail.value
  })
  },
  //点击登陆
  login() {
  let zhanghao = this.data.zhanghao
  let mima = this.data.mima
  console.log('账号', zhanghao, '密码', mima)
  if (zhanghao.length < 4) {
   wx.showToast({
    icon: 'none',
    title: '账号至少4位',
   })
   return
  }
  if (mima.length < 4) {
   wx.showToast({
    icon: 'none',
    title: '账号至少4位',
   })
   return
  }
  
  //登陆
  wx.cloud.database().collection('user').where({
   zhanghao: zhanghao
  }).get({
   success(res) {
    console.log("获取数据成功", res)
    let user = res.data[0]
    console.log("user", user)
    if (mima == user.mima) {
     console.log('登陆成功')
     wx.showToast({
      title: '登陆成功',
     })
     wx.navigateTo({
      url: '/pages/me/me',
     })
     //保存用户登陆状态
     wx.setStorageSync('user', user)
    } else {
     console.log('登陆失败')
     wx.showToast({
      icon: 'none',
      title: '账号或密码不正确',
     })
    }
   },
   fail(res) {
    console.log("获取数据失败", res)
   }
  })
  }
  })

(3)实现效果
在这里插入图片描述
5. 编写个人中心登陆和未登陆状态的展示,含退出登陆功能
(1)个人界面wxml文件

<!--pages/me/me.wxml-->
<!-- 未登录 -->
<view class="me" wx:if="{{!loginOK}}">
  <button class="denglu" type="primary" bindtap="denglu">登录</button>
  <button class="zhuce" type="primary" bindtap="zhuce">注册</button>
</view>
<!-- 登录成功 -->
<view wx:else class="login-ok" > 
  <text class="text">登录成功</text>
  <view>
    <text class="user">账号:{{name}}</text>
  </view>
  <button bindtap="tuichu">退出</button>
</view>

(2)个人界面的js逻辑文件

// pages/me/me.js
Page({
  data: {
  loginOK: false
  },
  //去登陆页
  denglu() {
  wx.navigateTo({
   url: '/pages/login/login',
  })
  },
  //去注册页
  zhuce() {
  wx.navigateTo({
   url: '/pages/index/index',
  })
  },
  onShow() {
  let user = wx.getStorageSync('user')
  if (user && user.name) {
   this.setData({
    loginOK: true,
    name: user.name
   })
  } else {
   this.setData({
    loginOK: false
   })
  }
  },
  
  //退出登陆
  tuichu() {
  wx.setStorageSync('user', null)
  let user = wx.getStorageSync('user')
  if (user && user.name) {
   this.setData({
    loginOK: true,
    name: user.name
   })
  } else {
   this.setData({
    loginOK: false
   })
  }
  }
  })

(3)实现效果
在这里插入图片描述
在这里插入图片描述
完整实现效果

四、总结

到这里我们就完整的实现了小程序的登录注册功能了,虽然比较简单,没有做密码加密等一些复杂的操作,但是我们基本的登录注册原理就是这样实现的,只有先把最基础的登录注册功能实现,对学习后面复杂的登录注册,验证码登录等一系列知识有所帮助。

完整小程序项目文件

以上是关于俺是菜鸟,俺想做一个俺android的登陆注册功能,利用socket通信,数据库是mysql。的主要内容,如果未能解决你的问题,请参考以下文章

Android上如何实现自动登陆功能?

用QT做个注册界面 注册的账号存入sqlite 登陆的时候怎么操作可以读取注册的新账号和密码

android studio 菜鸟实战项目 之 点击事件以及动态添加

input标签怎么才能只输入数字?

如何在Android手机中开发QQ账户登陆功能

android如何实现 登陆以及注册