Android-based simple chat tool-server side

Source: Internet
Author: User
Tags get ip

1, the database of MySQL, a total of 3 tables, a user table users, a friends list friend and a message form messages.

1      User table  UID             primary key automatically generated  userName        nickname  userpwd         password  usersex         gender  Userpho         user avatar with default avatar 2 friend table    Friend list  FID             primary key auto-generated   -- FK      User ID, foreign key           --Friend ID  fName           3 Messages           Table message sheet  mid                      Message ID, primary key automatically generated  - - FK from ID    Sender ID  --- FK to ID       receiver ID  msg                      Message content  mtime                    send time

2. Server-side architecture

3. Model Package Parsing

 Public classuser{//1User Class    PrivateString UserName;//User name    PrivateString userpwd;//User Password    PrivateString Usersex;//User Gender    PrivateString Userpho;//User Photos... Public classFriend {//2Friend class    Private intUid//User ID    Private intFuid;//Friend ID    PrivateString FName;//user's friend name... Public classFriendlistextendsarraylist<friend>{//3Friends List Class    /**     *      */    Private Static Final LongSerialversionuid = 1L; Privatefriendlist friendlist;  Publicfriendlist () {friendlist=NULL; }}
 Public class MESSAGES{//4 Message class     privateint  fromid;     Private int toid;     Private String msg;     Private String mtime;      Public Messages () {            }

4. DB Packet parsing

The main function is to load the class, get the MySQL database connection

public class DBConnection {public static final string dburl = "Jdbc:mysql://localhost:3306/qq";p ublic static final string DBUSER = "root";p ublic static final String dbpass = "root";p ublic static final String dbdriver = "Com.mysql.jdbc.Driver"; s tatic {try {class.forname (dbdriver);//Load Class} catch (ClassNotFoundException e) {e.printstacktrace ()}} return connectionpublic Connection GetConnect () throws Sqlexception{return drivermanager.getconnection (Dburl,dbuser, Dbpass);} Close resource public void close (Connection con, Statement STA, ResultSet rs) {try {rs.close (); {con.close ();} if (STA! = null) {Sta.close ();}} catch (SQLException e) {e.printstacktrace ();}}}

5. Util Package Parsing

The first class of packager

public Class Packager {//Parse public string Loginpackager (string operate,string friends,string result) for login packets { StringBuffer mes = new StringBuffer (""); Mes.append ("Operate:" + operate + "\ n"); Mes.append ("content:" + friends); Mes.append ("Result:" + result + "\ n"); return mes.tostring ();} Analysis public string Sendpackager (string operate,string msg,string result) for sending packets {stringbuffer mes = new StringBuffer ("") ; Mes.append ("Operate:" + operate + "\ n"); Mes.append ("Content:" + "\ n"); Mes.append ("Result:" + result + "\ n"); return MES.T Ostring ();}}

The second class of parser

public class Parser {//Parse class//For resolving what type of request is obtained, such as login, send message public string getoperate (string request) {string[] message = Request . Split ("\ n"); String operate = message[0].substring (8,message[0].length ()); return operate;} Gets the content public string getcontent (string request) {string[] message = Request.split ("\ n"); String content = message[1].substring (8,message[1].length ()); return content;} Gets the message sent by public Messages parsemessages (String content) {string[] mes = Content.split ("#"); int toid = Integer.parseint ( Mes[0]); String message = Mes[1]; Messages msg = new Messages (); msg.settoid (toid); msg.setmsg (message); return msg;} Resolves the string to a user class, returning the user class public Parseuser (string content) {//delimiter = #string[] mes = Content.split ("#");//The first is the user name, The second one is the password string userName = Mes[0]; String userpwd = mes[1]; User user = new user (); user.setusername (userName); user.setuserpwd (userpwd); return user;}}

  

6. Controll Package Parsing

Controller class parsing

Controller public class Controller {//parameterless constructor public controller () {}//corresponding request public string Doresponse (String request,string IP) { Parser Parser = new Parser (); String operate = Parser.getoperate (request),//What is used to parse the user's requested action is string content = parser.getcontent (request);// Gets the content of the request string response = null;//the corresponding string friends = null;//friend if ("Login". Equals (operate)) {//Determines whether the login request is an int uid = login (c ontent);//Returns the user's ID if no user returns 0String result = Null;if (uid! = 0) {//Adds the user's primary key and IP address to the Management client class Manageclients.addips (new Integer (UID), IP); result = "success";//If the login is successful, then get all the friends List of the user friends = Getfriends (UID);} Else{result = "fail";//Login failed}packager Packager = New Packager (); response = Packager.loginpackager (Operate,friends, result);} else if ("SendMessage". Equals (operate)) {//If the message is sent messages msg = parser.parsemessages (content); int toid = Msg.gettoid () ;//Find the recipient's idstring ipaddress = ManageClients.ips.get (new Integer (toid)). toString ();//Get IP address by id serverthread sendto = (Serverthread) ManageClients.clients.get (ipaddress);//Get the thread SE of the recipient by IP addressNdto.send (Msg.getmsg ());//Send Message to Sender Packager Packager = New Packager (); String result = "success"; response = Packager.sendpackager (Operate,null,result);} return response;} Public String getfriends (int uid) {String sql = ' Select Fid,uid,fuid,fname from friend where uid= ' + uid;dbconnection DBC = new DBConnection (); Connection con = null; Statement sta = null; ResultSet rs = null; StringBuilder sb = new StringBuilder (""); try {con = dbc.getconnect (); con = Dbc.getconnect (); sta = Con.createstatement (); r s = sta.executequery (sql), while (Rs.next ()) {Sb.append (Rs.getint (1) + "#" + rs.getint (2) + "#" + rs.getint (3) + "#" + rs.gets Tring (4) + "\ n");}} catch (SQLException e) {e.printstacktrace ();} return sb.tostring ();} public int Login (String content) {//login operation, login successful, return friend list, otherwise return error cause parser parser = new parser (); User user = Parser.parseuser (content);//Get the Users class//And then go to the database to query whether there is a user, if there is a user, then return the user's primary key idstring sql = "Select Uid,userpwd From user where username= ' "+ user.getusername () +" ' ";D bconnection DBC = new DBConnection ();Connection con = null; Statement sta = null; ResultSet rs = null; String dbpwd = Null;int uid = 0;try {con = Dbc.getconnect (); sta = Con.createstatement (); rs = sta.executequery (sql); while (R S.next ()) {uid = rs.getint (1);d bpwd = rs.getstring (2);}} catch (SQLException e) {e.printstacktrace ();} Finally{dbc.close (Con, STA, RS);} if (dbpwd! = null && dbpwd.equals (USER.GETUSERPWD ()) && uid! = 0) {return uid;} Else{uid = 0;return uid;}}

7. Server Package parsing

The 7.1 server class opens the listening port, constantly listening to the requested user

public class Server {public static void main (string[] args) {new Server ();} Public Server () {ServerSocket serversocket = null; Socket socket = null;try {serversocket = new ServerSocket (5000); SYSTEM.OUT.PRINTLN ("Server is already started, listening on port 5000"); while (true) {socket = serversocket.accept (); String IP = socket.getlocaladdress (). gethostaddress (); Serverthread st = new Serverthread (SOCKET,IP);//server thread St.start (); Manageclients.addclients (IP, ST);//Add the thread to the Manageclients class int port = Socket.getport (); SYSTEM.OUT.PRINTLN ("Client IP on Connection:" + IP + ", port number:" + port);}} catch (IOException e) {e.printstacktrace ();}}}

7.2 Serverthread class, for forwarding messages

public class Serverthread extends Thread{private Socket socket;private String ip;private inputstream in;private outputstr EAM out;private static final int SIZE = 1024;public Socket Getsocket () {return socket;} Public Serverthread (Socket socket,string IP) {this.socket = Socket;this.ip = ip;try {in = Socket.getinputstream (); Cket.getoutputstream ();} catch (IOException e) {e.printstacktrace ();}} public void Send (String mes) {try {out.write (mes.getbytes ()); Out.flush ();} catch (IOException e) {e.printstacktrace ()}} public void Close () {try {if (in! = null) {in.close (); in = null;} if (out! = null) {out.close (); out = null;} if (socket! = NULL) {socket.close (); socket = null;}} catch (IOException e) {e.printstacktrace ();}} public void Run () {while (true) {try {byte[] buffer = new Byte[size];int index = in.read (buffer); String message = new string (buffer,0,index);//Gets the request sent by the client parser parser = new parser (); String operate = parser.getoperate (message); Controller Controller = new Controller (); if (operate.eQuals ("Exit")) {break;} String response = Controller.doresponse (MESSAGE,IP);//The server processes the message sent over, if not the harvest//operation is not exitif (response! = NULL) Send ( Response);//Send the result of the request operation to the client} catch (IOException e) {e.printstacktrace ();} Finally{close ();}}}

7.3 manageclients

public class Manageclients {//admin client, HashMap Store user IP and thread key values to public   static hashmap<string,serverthread> Clients = new hashmap<string,serverthread> ()//string sender//used for the key value between the user primary key and the IP to public  static hashmap< integer,string> ips = new hashmap<integer,string> ();p ublic static  void Addclients (String senderip, Serverthread St) {clients.put (Senderip, ST);} public static void Addips (Integer i, String IP) {ips.put (i, IP);}}

End of server end, start the main function in server, listen for client requests

Android-based simple chat tool-server side

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.