Android实现实时通信示例
程序员文章站
2023-11-28 15:53:58
我们今天来聊下如何做实时通讯(先给知识点,实现原理,最后给出实现实时通信的具体代码--使用工具 android studio)
现在先说下用到的知识点:
jav...
我们今天来聊下如何做实时通讯(先给知识点,实现原理,最后给出实现实时通信的具体代码--使用工具 android studio)
现在先说下用到的知识点:
- java的socket包括服务端和客户端, 这个是用来实现通信
- java的多线程,这个是用来实现实时通信
- java的线程通信,实现界面实时更新
实现原理
就是将发送端,接收端分别放进一个线程去运行,然后利用线程通信类handler来进行线程间的通信,实现界面的通信
实现代码:
权限
<uses-permission android:name="android.permission.access_wifi_state"></uses-permission> <uses-permission android:name="android.permission.change_wifi_state"></uses-permission> <uses-permission android:name="android.permission.wake_lock"></uses-permission> <uses-permission android:name="android.permission.internet"/>
layout
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.ysp.asus.experiment_02.mainactivity" android:weightsum="10"> <button android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#03a9f4" android:textcolor="#ffffffff" android:textsize="30sp" android:text="ip" android:id="@+id/myip"/> <!--点击开始聊天--> <linearlayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:weightsum="10"> <!--ip--> <edittext android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:id="@+id/ip" android:hint="请写入对方通讯地址ip" /> </linearlayout> <!--显示聊天记录--> <edittext android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="7" android:gravity="top" android:editable="false" android:scrollbars="vertical" android:id="@+id/receivemessage"/> <!--用于写入发送信息和按钮--> <linearlayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> <edittext android:layout_width="0dp" android:layout_weight="8" android:layout_height="match_parent" android:hint="填写要发送的信息" android:id="@+id/message"/> <button android:layout_width="0dp" android:layout_weight="2" android:layout_height="match_parent" android:text="发送消息" android:background="#03a9f4" android:textcolor="#ffffffff" android:id="@+id/sendmessage"/> </linearlayout> </linearlayout>
客户端类
package com.ysp.asus.experiment_02; import java.io.bufferedreader; import java.io.bufferedwriter; import java.io.ioexception; import java.io.inputstreamreader; import java.io.outputstreamwriter; import java.net.socket; import java.net.unknownhostexception; /** * created by asus on 2017/3/16. */ public class chatclient { public socket requestsocket(string host) throws unknownhostexception,ioexception{ socket socket=new socket(host,5000); return socket; } public void sendmsg(socket socket,string msg)throws ioexception{ bufferedwriter writer=new bufferedwriter( new outputstreamwriter(socket.getoutputstream()) ); writer.write(msg.replace("\n","")+"\n"); writer.flush(); } public string receivemsg(socket socket)throws ioexception{ bufferedreader reader=new bufferedreader( new inputstreamreader(socket.getinputstream()) ); string txt=reader.readline(); return txt; } }
服务端类
package com.ysp.asus.experiment_02; import android.os.handler; import android.os.message; import android.util.log; import java.io.bufferedreader; import java.io.bufferedwriter; import java.io.ioexception; import java.io.inputstreamreader; import java.io.outputstreamwriter; import java.net.serversocket; import java.net.socket; /** * created by asus on 2017/3/16. */ public class chatserver extends thread { public chatserver() throws ioexception { createsocket(); } public void run(){ socket client; string txt; log.i("信息","成功开始服务器,端口为:"+port); try{ while (true){ client=responsesocket(); while(true){ txt=receivemsg(client); system.out.println(txt); message message1 = new message(); message1.obj =txt+"\n"; com.ysp.asus.experiment_02.mainactivity.handler.sendmessage(message1); if(true) break; } // closesocket(client); } }catch (ioexception e){ } } private handler mhandler = new handler(){ public void handlemessage(message msg) { }; }; public serversocket server=null; private int port =5000; private bufferedwriter writer; private bufferedreader reader; public void createsocket() throws ioexception{ server=new serversocket(port,100); } public socket responsesocket() throws ioexception{ socket client =server.accept(); return client; } public void closesocket(socket socket) throws ioexception{ reader.close(); socket.close(); server.close(); } public void sendmsg(socket socket,string string)throws ioexception{ writer=new bufferedwriter( new outputstreamwriter(socket.getoutputstream()) ); writer.write("msg"+string); writer.flush(); } public string receivemsg(socket socket) throws ioexception{ reader=new bufferedreader( new inputstreamreader(socket.getinputstream()) ); string txt ="对方:"+reader.readline(); return txt; } }
mainactivity类
package com.ysp.asus.experiment_02; import android.content.context; import android.net.wifi.wifiinfo; import android.net.wifi.wifimanager; import android.os.bundle; import android.os.handler; import android.os.message; import android.support.v7.app.appcompatactivity; import android.text.clipboardmanager; import android.util.log; import android.view.view; import android.view.inputmethod.inputmethodmanager; import android.widget.button; import android.widget.edittext; import java.io.ioexception; import java.net.socket; import static com.ysp.asus.experiment_02.r.id.receivemessage; public class mainactivity extends appcompatactivity { final chatserver chatserver=null; static string text=""; static edittext receivemessage=null; final chatclient chatclient = new chatclient(); @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // 定义相关的变量 receivemessage=(edittext) findviewbyid(receivemessage); final edittext message=(edittext)findviewbyid(r.id.message); final edittext ip = (edittext)findviewbyid(r.id.ip); final button sendmessage = (button)findviewbyid(r.id.sendmessage); final button myip =(button) findviewbyid(r.id.myip); // 获取wifi下的ip地址并显示 //获取wifi服务 wifimanager wifimanager = (wifimanager) getsystemservice(context.wifi_service); //判断wifi是否开启 if (!wifimanager.iswifienabled()) { wifimanager.setwifienabled(true); } wifiinfo wifiinfo = wifimanager.getconnectioninfo(); int ipaddress = wifiinfo.getipaddress(); string ip = inttoip(ipaddress); myip.settext(ip); // 点击实现复制内容到粘贴板 myip.setclickable(true); myip.setonclicklistener(new button.onclicklistener() { public void onclick(view arg0) { clipboardmanager cm = (clipboardmanager) getsystemservice(context.clipboard_service); // 将文本内容放到系统剪贴板里。 cm.settext(myip.gettext().tostring()); } }); // 初始化看是服务器 try{ chatserver chatserver=new chatserver(); chatserver.start(); }catch(ioexception e){ log.e("错误","开启服务器失败"); e.printstacktrace(); } // 点击按钮发送数据给相应的ip地址 sendmessage.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { hidekeyboard(sendmessage); new thread(new runnable() { @override public void run() { try { socket socket=chatclient.requestsocket(ip.gettext().tostring()); chatclient.sendmsg(socket,message.gettext().tostring()); message message1 = new message(); message1.obj ="自己: "+message.gettext().tostring()+"\n"; handler.sendmessage(message1); }catch (ioexception e){ log.e("错误","发送失败"); } } }).start(); } }); } public static handler handler=new handler(){ @override public void handlemessage(message msg) { super.handlemessage(msg); log.i("信息","其他线程发过来:"+msg); text+=msg.obj.tostring(); receivemessage.settext(text); receivemessage.setselection(receivemessage.gettext().length(), receivemessage.gettext().length()); } }; // 用于将结果以ip的形式放出 private string inttoip(int i) { return (i & 0xff ) + "." + ((i >> 8 ) & 0xff) + "." + ((i >> 16 ) & 0xff) + "." + ( i >> 24 & 0xff) ; } //隐藏虚拟键盘 public static void hidekeyboard(view v) { inputmethodmanager imm = ( inputmethodmanager ) v.getcontext( ).getsystemservice( context.input_method_service ); if ( imm.isactive( ) ) { imm.hidesoftinputfromwindow( v.getapplicationwindowtoken( ) , 0 ); } } }
效果展示
demo示例下载:http://pan.baidu.com/s/1hr2oizq
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。