Socket-based chat applications for Android (2)

Source: Internet
Author: User
Preface

I haven't written a BLOG for a long time. I promised to write a chat demo between customers (Friends) When I was writing an Android chat room, the Socket-based chat room of Android has implemented the communication function through Socket broadcast.

The following is a bubble chat APP that I wrote similar to most chat software. All functions are my own ideas. I still don't know how to implement the successful examples on the market. Therefore, you can only learn by reference or share your case with me.

Function
  • One-to-one chat, non-chat room
  • Friend list
  • Online and offline friends (Real-time update)
  • Bubble real-time chat window
  • Send offline information
Basic Principles

Previous chat room principle: every time the client Socket connects to the ServerSocket, the program adds the corresponding Socket to the clients set for saving and starts a thread for the Socket, this thread is responsible for processing all the communication tasks of the Socket. After the server thread reads the client data, the program traverses the clients set and sends the data to each Socket in the clients set once.

One-to-one chat: the Server stores all Clients sockets through Map and uses the Client user ID as the Map key. When A sends information to B, the Server searches for B's Socket, establish their communication channels.

Server

This time I added two Socket sets to the server. One is used to process Online/Offline users, and the other is used to process communication information between users.

1 static Map<String, Socket> socketMap = new HashMap<String, Socket>();
2 static Map<String, Socket> onlineMap = new HashMap<String, Socket>();

Clients goes online and goes offline. The Server filters and notifies its online Friends. Clients receives the online status of Friends and modifies the Friends List.

1 //save client's name ,online
2 //...
3 getnameString = str.substring(config.PROTOCOL_KEY.length()+config.PROTOCOL_ONLINE.length());
4 Server.onlineMap.put(getnameString, s);
5 //...
6 //update online friends
7 DataOutputStream onlineDOS = new DataOutputStream (Server.onlineMap.get(clientKey).getOutputStream());
8 onlineDOS.writeUTF(config.PROTOCOL_FRIENDS_START+onlineString+config.PROTOCOL_FRIENDS_END);
9 onlineDOS.flush();

For chat, I use A custom encryption character to mark each Client, for example, the information sent by Client, the header of this message carries A special symbol recognized by both the server and the Client. It is used for character processing to find the user information of this message. Similarly, the communication object of Client A also uses this method.

After finding the target object of ClientA, we can find this Socket channel and they can have a one-to-one conversation.

1 //send msg to friend
2 DataOutputStream ndos = new DataOutputStream (Server.socketMap.get(forname).getOutputStream());
3 ndos.writeUTF(fromname+date+"\n"+forchat);
4 ndos.flush();

 

For offline information, this is mainly the server's function. I use mySql to save data. Client A sends A message to Client B in the offline status. The Server checks whether Client B is online. If it is offline, the Server first saves the message to mySql; when Client B is online, the server will find its offline information. If there is unread information, it will send it in time. Client B will be able to receive offline information ( ̄)

Client Clients

To chat with multiple friends at the same time (different window threads), ContentProvider is used to monitor the changes of chat data, this allows activities that are not in the current chat window to receive messages from friends and print them together.

1 // monitor chat data changes
2 getContentResolver (). registerContentObserver (DataChangeProvider. CONTENT_URI, true, cob );

How does the background receive messages from friends? As mentioned above, the Server has a SocketMap set, which records the user's communication Socket. When there is information, the client's backend WaitMsg () will receive and process the sent information.

1 private Runnable waitThread = new Runnable() {
2 public void run() {
3 System.out.println("wait running!");
4 WaitMsg();
5 }
6 };

For the Online/Offline status, the Friends List Activity ReceiveMsg () monitors the Friends status sent by the Server and updates the ListActivity list in a timely manner.

1 // update the friend Database
2 fanDS. updateData (reMsg, name );
3 // obtain the friend list
4 fansArray = fanDS. getFans ();
5
6 friends = new Friends (fansArray, reMsg, name );
7 friendList = friends. getFriends ();
Summary

Compared with chat rooms, one-to-one chat mainly records the sockets of each Client, so that each communication action has a target object. The Server acts as a messenger to connect the sockets of the two, enable communication and chat between the two.

This is the C/S mode of communication under the TCP/IP protocol, as well as the UDP protocol, the P2P mode is worth learning.

There are too many demo codes, so we will not post them here. If necessary, please leave your mailbox.

If you like this article, please check it out.

 

 

My Sina Weibo

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.