怎么在Android应用中实现一个实时通信功能
今天就跟大家聊聊有关怎么在Android应用中实现一个实时通信功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
成都创新互联公司-专业网站定制、快速模板网站建设、高性价比泸水网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式泸水网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖泸水地区。费用合理售后完善,10多年实体公司更值得信赖。
实现原理
就是将发送端,接收端分别放进一个线程去运行,然后利用线程通信类handler来进行线程间的通信,实现界面的通信
实现代码:
权限
Layout
客户端类
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 ); } } }
看完上述内容,你们对怎么在Android应用中实现一个实时通信功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。
网站栏目:怎么在Android应用中实现一个实时通信功能
本文链接:http://azwzsj.com/article/jepdoh.html