Android之Socket通讯

2024-08-31 09:48
文章标签 android 通讯 socket

本文主要是介绍Android之Socket通讯,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Android里面使用Socket与服务器之间进行通讯:

首先建立一个SocThread类

 
package com.junto.sockettest;import android.content.Context;
import android.content.SharedPreferences;
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.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;/*** Created by WangJinyong on 2018/6/30.*/public class SocThread extends Thread {private String ip = "114.116.64.184";private int port = 9667;private String TAG = "socket thread";private int timeout = 10000;public Socket client = null;PrintWriter out;BufferedReader in;public boolean isRun = true;Handler inHandler;Handler outHandler;Context ctx;private String TAG1 = "===Send===";SharedPreferences sp;public SocThread(Handler handlerin, Handler handlerout, Context context) {inHandler = handlerin;outHandler = handlerout;ctx = context;Log.i(TAG, "创建线程socket");}/*** 连接socket服务器*/public void conn() {try {initdate();Log.i(TAG, "连接中……");client = new Socket(ip, port);client.setSoTimeout(timeout);// 设置阻塞时间Log.i(TAG, "连接成功");in = new BufferedReader(new InputStreamReader(client.getInputStream()));out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);Log.i(TAG, "输入输出流获取成功");} catch (UnknownHostException e) {Log.i(TAG, "连接错误UnknownHostException 重新获取");e.printStackTrace();conn();} catch (IOException e) {Log.i(TAG, "连接服务器io错误");e.printStackTrace();} catch (Exception e) {Log.i(TAG, "连接服务器错误Exception" + e.getMessage());e.printStackTrace();}}public void initdate() {sp = ctx.getSharedPreferences("SP", ctx.MODE_PRIVATE);ip = sp.getString("ipstr", ip);port = Integer.parseInt(sp.getString("port", String.valueOf(port)));Log.i(TAG, "获取到ip端口:" + ip + ";" + port);}/*** 实时接受数据*/@Overridepublic void run() {Log.i(TAG, "线程socket开始运行");conn();Log.i(TAG, "1.run开始");String line = "";while (isRun) {try {if (client != null) {Log.i(TAG, "2.检测数据");while ((line = in.readLine()) != null) {Log.i(TAG, "3.getdata" + line + " len=" + line.length());Log.i(TAG, "4.start set Message");Message msg = inHandler.obtainMessage();msg.obj = line;inHandler.sendMessage(msg);// 结果返回给UI处理Log.i(TAG1, "5.send to handler");}} else {Log.i(TAG, "没有可用连接");conn();}} catch (Exception e) {Log.i(TAG, "数据接收错误" + e.getMessage());e.printStackTrace();}}}/*** 发送数据** @param mess*/public void Send(String mess) {try {if (client != null) {Log.i(TAG1, "发送" + mess + "至"+ client.getInetAddress().getHostAddress() + ":"+ String.valueOf(client.getPort()));out.println(mess);out.flush();Log.i(TAG1, "发送成功");Message msg = outHandler.obtainMessage();msg.obj = mess;msg.what = 1;outHandler.sendMessage(msg);// 结果返回给UI处理} else {Log.i(TAG, "client 不存在");Message msg = outHandler.obtainMessage();msg.obj = mess;msg.what = 0;outHandler.sendMessage(msg);// 结果返回给UI处理Log.i(TAG, "连接不存在重新连接");conn();}} catch (Exception e) {Log.i(TAG1, "send error");e.printStackTrace();} finally {Log.i(TAG1, "发送完毕");}}/*** 关闭连接*/public void close() {try {if (client != null) {Log.i(TAG, "close in");in.close();Log.i(TAG, "close out");out.close();Log.i(TAG, "close client");client.close();}} catch (Exception e) {Log.i(TAG, "close err");e.printStackTrace();}}
}
 

通讯的Activity类Client

package com.junto.sockettest;import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;/*** Created by WangJinyong on 2018/6/30.*/public class Client extends Activity {private String TAG = "===Client===";private TextView tv1 = null;Handler mhandler;Handler mhandlerSend;EditText edtsendms;Button btnsend;private String sendstr = "";private Context ctx;SocThread socketThread;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.client);tv1 = (TextView) findViewById(R.id.tv1);btnsend = (Button) findViewById(R.id.button1);ctx = Client.this;edtsendms = (EditText) findViewById(R.id.editText1);mhandler = new Handler() {@Overridepublic void handleMessage(Message msg) {try {Log.i(TAG, "mhandler接收到msg=" + msg.what);if (msg.obj != null) {
//                        byte[] objStr2 = (byte[]) msg.obj;
//                        Log.e("tag","objStr2="+objStr2);String s = msg.obj.toString();if (s.trim().length() > 0) {Log.i(TAG, "mhandler接收到obj=" + s);Log.i(TAG, "开始更新UI");tv1.append("Server:" + s);Log.i(TAG, "更新UI完毕");} else {Log.i(TAG, "没有数据返回不更新");}}} catch (Exception ee) {Log.i(TAG, "加载过程出现异常");ee.printStackTrace();}}};mhandlerSend = new Handler() {@Overridepublic void handleMessage(Message msg) {try {Log.i(TAG, "mhandlerSend接收到msg.what=" + msg.what);String s = msg.obj.toString();if (msg.what == 1) {tv1.append("\n ME: " + s + "      发送成功");} else {tv1.append("\n ME: " + s + "     发送失败");}} catch (Exception ee) {Log.i(TAG, "加载过程出现异常");ee.printStackTrace();}}};startSocket();btnsend.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// 发送数据Log.i(TAG, "准备发送数据");sendstr = edtsendms.getText().toString().trim();socketThread.Send(sendstr);}});}public void startSocket() {socketThread = new SocThread(mhandler, mhandlerSend, ctx);socketThread.start();}private void stopSocket() {socketThread.isRun = false;socketThread.close();socketThread = null;Log.i(TAG, "Socket已终止");}@Overrideprotected void onStart() {super.onStart();Log.e(TAG, "start onStart~~~");}@Overrideprotected void onRestart() {super.onRestart();Log.e(TAG, "start onRestart~~~");startSocket();}@Overrideprotected void onResume() {super.onResume();Log.e(TAG, "start onResume~~~");}@Overrideprotected void onPause() {super.onPause();Log.e(TAG, "start onPause~~~");}@Overrideprotected void onStop() {super.onStop();Log.e(TAG, "start onStop~~~");stopSocket();}@Overrideprotected void onDestroy() {super.onDestroy();Log.e(TAG, "start onDestroy~~~");}}
client的XML布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_centerVertical="true"android:text="接收到的信息" /><TextViewandroid:id="@+id/tv1"android:layout_width="150dp"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_centerVertical="true"android:layout_weight="0.25"android:text="" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_centerVertical="true"android:text="请输入发送内容" /><EditTextandroid:id="@+id/editText1"android:layout_width="match_parent"android:layout_height="wrap_content"android:ems="10"><requestFocus /></EditText><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="发送" /></LinearLayout></LinearLayout>
在AndroidManifest.xml添加网络权限:
<uses-permission android:name="android.permission.INTERNET"/>

这篇关于Android之Socket通讯的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1123563

相关文章

如何解决Druid线程池Cause:java.sql.SQLRecoverableException:IO错误:Socket read timed out的问题

《如何解决Druid线程池Cause:java.sql.SQLRecoverableException:IO错误:Socketreadtimedout的问题》:本文主要介绍解决Druid线程... 目录异常信息触发场景找到版本发布更新的说明从版本更新信息可以看到该默认逻辑已经去除总结异常信息触发场景复

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

C#使用MQTTnet实现服务端与客户端的通讯的示例

《C#使用MQTTnet实现服务端与客户端的通讯的示例》本文主要介绍了C#使用MQTTnet实现服务端与客户端的通讯的示例,包括协议特性、连接管理、QoS机制和安全策略,具有一定的参考价值,感兴趣的可... 目录一、MQTT 协议简介二、MQTT 协议核心特性三、MQTTNET 库的核心功能四、服务端(BR

Android NDK版本迭代与FFmpeg交叉编译完全指南

《AndroidNDK版本迭代与FFmpeg交叉编译完全指南》在Android开发中,使用NDK进行原生代码开发是一项常见需求,特别是当我们需要集成FFmpeg这样的多媒体处理库时,本文将深入分析A... 目录一、android NDK版本迭代分界线二、FFmpeg交叉编译关键注意事项三、完整编译脚本示例四

Android与iOS设备MAC地址生成原理及Java实现详解

《Android与iOS设备MAC地址生成原理及Java实现详解》在无线网络通信中,MAC(MediaAccessControl)地址是设备的唯一网络标识符,本文主要介绍了Android与iOS设备M... 目录引言1. MAC地址基础1.1 MAC地址的组成1.2 MAC地址的分类2. android与I

Android 实现一个隐私弹窗功能

《Android实现一个隐私弹窗功能》:本文主要介绍Android实现一个隐私弹窗功能,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 效果图如下:1. 设置同意、退出、点击用户协议、点击隐私协议的函数参数2. 《用户协议》、《隐私政策》设置成可点击的,且颜色要区分出来res/l

Android实现一键录屏功能(附源码)

《Android实现一键录屏功能(附源码)》在Android5.0及以上版本,系统提供了MediaProjectionAPI,允许应用在用户授权下录制屏幕内容并输出到视频文件,所以本文将基于此实现一个... 目录一、项目介绍二、相关技术与原理三、系统权限与用户授权四、项目架构与流程五、环境配置与依赖六、完整

Android 12解决push framework.jar无法开机的方法小结

《Android12解决pushframework.jar无法开机的方法小结》:本文主要介绍在Android12中解决pushframework.jar无法开机的方法,包括编译指令、框架层和s... 目录1. android 编译指令1.1 framework层的编译指令1.2 替换framework.ja

Android开发环境配置避坑指南

《Android开发环境配置避坑指南》本文主要介绍了Android开发环境配置过程中遇到的问题及解决方案,包括VPN注意事项、工具版本统一、Gerrit邮箱配置、Git拉取和提交代码、MergevsR... 目录网络环境:VPN 注意事项工具版本统一:android Studio & JDKGerrit的邮

Android实现定时任务的几种方式汇总(附源码)

《Android实现定时任务的几种方式汇总(附源码)》在Android应用中,定时任务(ScheduledTask)的需求几乎无处不在:从定时刷新数据、定时备份、定时推送通知,到夜间静默下载、循环执行... 目录一、项目介绍1. 背景与意义二、相关基础知识与系统约束三、方案一:Handler.postDel