欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

Android实现实时通信示例

时间:2022-07-20 10:32:50|栏目:Android代码|点击:

我们今天来聊下如何做实时通讯(先给知识点,实现原理,最后给出实现实时通信的具体代码--使用工具 android studio)
现在先说下用到的知识点:

  1. java的socket包括服务端和客户端,  这个是用来实现通信
  2. java的多线程,这个是用来实现实时通信
  3. 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

上一篇:Kotlin中的对象表达式和对象声明的具体使用

栏    目:Android代码

下一篇:mui,h5+中实现控制页面load显示 原创

本文标题:Android实现实时通信示例

本文地址:http://www.codeinn.net/misctech/208304.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有