Study Notes for Android (31)-socket chat room for network communication

Source: Internet
Author: User
Tags sendmsg

In the previous blog, I briefly introduced the simple communication of socket, which will be used in this blog. The next example is to refer to the secrets of Android Application development. However, there are some minor issues, such as character encoding. The following describes the implementation process.

1. Server:

Import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. printwriter; import java.net. serversocket; import java.net. socket; import Java. util. arraylist; import Java. util. list; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors; public class server {Private Static int Port = 54327; Private Static list <socket> msocketlist = new ar Raylist <socket> (); Private executorservice mexcutorservice; private serversocket mserversocket; public static void main (string [] ARGs) {new server ();} public server () {try {mserversocket = new serversocket (port); mexcutorservice = executors. newcachedthreadpool (); Socket Client = NULL; while (true) {client = mserversocket.accept(~~msocketlist.add(client=%mexcutorservice.exe cute (New threadserver (client ));}} Catch (exception e) {// todo: handle finished tione. printstacktrace () ;}} static class threadserver implements runnable {private socket msocket; private bufferedreader mbufferedreader; private printwriter mprintwriter; private string MSG = ""; Public threadserver (Socket socket) throws ioexception {This. msocket = socket; mbufferedreader = new bufferedreader (New inputstreamreader (msocket. getinputstream (), "Ut F-8 "); mprintwriter = new printwriter (msocket. getoutputstream (), true); MSG = mbufferedreader. readline (); system. out. println (MSG); sendmessage () ;}@ overridepublic void run () {// todo auto-generated method stubtry {While (MSG = mbufferedreader. readline ())! = NULL) {If (MSG. trim (). equals ("Mo: Exit") {MSG = "The ing... "; system. out. println ("read -->" + MSG); sendmessage (); msocketlist. remove (msocket); mbufferedreader. close (); mprintwriter. close (); msocket. close (); break;} system. out. println ("read -->" + MSG); sendmessage () ;}} catch (exception e) {// todo: handle exceptionsystem. out. println (E. getmessage () ;}} private void sendmessage () throws ioexception {for (Socket Client: msocketlist) {mprintwriter = new printwriter (client. getoutputstream (), true); mprintwriter. println (MSG );}}}}

2. Client:

Package COM. ideal. socket; import Java. io. bufferedreader; import Java. io. inputstreamreader; import Java. io. printwriter; import java.net. socket; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; import android. widget. textview; P Ublic class net_socketclientactivity extends activity {private edittext Muser = NULL; // enter private button mlogin = NULL; private edittext msendmsg = NULL; // enter private button msend = NULL; private textview mtextview = NULL; // record private socket msocket; private thread mthread; private bufferedreader mbufferedreader; private printwriter mprintwriter; private string name = ""; private string MSG = ""; /** called whe N the activity is first created. * // @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); Muser = (edittext) findviewbyid (R. id. user); mlogin = (button) findviewbyid (R. id. login); msendmsg = (edittext) findviewbyid (R. id. sendmsg); msend = (button) findviewbyid (R. id. sentbtn); mtextview = (textview) findviewbyid (R. id. allmassage); mlogin. seton Clicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubtry {mlogin. setvisibility (view. gone); Muser. setvisibility (view. gone); msocket = new socket ("172.31.100.50", 54327); // transcode mbufferedreader = new bufferedreader (New inputstreamreader (msocket. getinputstream (), "GBK"); mprintwriter = new printwriter (msocket. getoutputstream (), true); name = Muser. gettex T (). tostring (); try {mprintwriter. println (name + ": Login... "); mprintwriter. flush ();} catch (exception e) {// todo: handle exceptionsystem. out. println (E. getmessage () ;}} catch (exception e) {// todo: handle exception }}); msend. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stub try {string sendmsg = msendmsg. gettext (). tostring (); mprintwri Ter. println (name + ":" + sendmsg); mprintwriter. flush ();} catch (exception e) {// todo: handle exceptionsystem. out. println (E. getmessage () ;}}); mthread = new thread (mrunnable); mthread. start ();} private runnable mrunnable = new runnable () {@ overridepublic void run () {// todo auto-generated method stubwhile (true) {try {MSG = mbufferedreader. readline (); If (MSG! = NULL) {mhandler. sendmessage (mhandler. obtainmessage ();} else {break ;}} catch (exception e) {// todo: handle exception }}}; handler mhandler = new handler () {public void handlemessage (Message MSG) {super. handlemessage (MSG); try {mtextview. append ("\ n" + MSG);} catch (exception e) {// todo: handle exception }}};}

XML:

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: Orientation = "vertical"> <edittext Android: id = "@ + ID/user" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"/> <button Android: Id = "@ + ID/login" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: text = "login"/> <edittext Android: Id = "@ + ID/sendmsg" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"/> <button Android: Id = "@ + ID/sentbtn" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: text = "send"/> <textview Android: Id = "@ + ID/allmassage" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent"/> </linearlayout>

See:

Login...

Login successful, waiting for sending information...

Send information

Note: The above only uses the simulator as the client and PC as the server to communicate, of course, you can open several more simulators, and these users are chatting at the same time. If you are using a simulator in the same lab, the simulator used on the other computer can also communicate with the simulator on other computers.

Problems:

1. At the beginning, strings cannot be properly displayed on both the simulator and PC, and transcoding was learned later. From the code above, we can see that:

On the server:

mBufferedReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream(),"UTF-8"));

On the client:

mBufferedReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream(),"GBK"));

2. The simulator can fully communicate with the PC, but cannot communicate if the real machine is used as the client. The reason is that socket communication can only be implemented in the same network segment. Due to the problem of conditions, you can try again later in the next day.

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.