使用Socket实现安卓中IPC

2024-05-27 06:48

本文主要是介绍使用Socket实现安卓中IPC,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket。
  建立网络通信连接至少要一对端口号(socket)。socket本质是编程接口(API),对TCP/IP的封装,TCP/IP也要提供可供程序员做网络开发所用的接口,这就是Socket编程接口;HTTP是轿车,提供了封装或者显示数据的具体形式;Socket是发动机,提供了网络通信的能力。
  Socket的英文原义是“孔”或“插座”。作为BSD UNIX的进程通信机制,取后一种意思。通常也称作”套接字”,用于描述IP地址和端口,是一个通信链的句柄,可以用来实现不同虚拟机或不同计算机之间的通信。在Internet上的主机一般运行了多个服务软件,同时提供几种服务。每种服务都打开一个Socket,并绑定到一个端口上,不同的端口对应于不同的服务。Socket正如其英文原意那样,像一个多孔插座。一台主机犹如布满各种插座的房间,每个插座有一个编号,有的插座提供220伏交流电, 有的提供110伏交流电,有的则提供有线电视节目。 客户软件将插头插到不同编号的插座,就可以得到不同的服务。

在Android中使用Socket实现聊天室功能

public class TCPClientActivity extends Activity implements OnClickListener {private static final int MESSAGE_RECEIVE_NEW_MSG = 1;private static final int MESSAGE_SOCKET_CONNECTED = 2;private Button mSendButton;private TextView mMessageTextView;private EditText mMessageEditText;private PrintWriter mPrintWriter;private Socket mClientSocket;@SuppressLint("HandlerLeak")private Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case MESSAGE_RECEIVE_NEW_MSG: {mMessageTextView.setText(mMessageTextView.getText()+ (String) msg.obj);break;}case MESSAGE_SOCKET_CONNECTED: {mSendButton.setEnabled(true);break;}default:break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_tcpclient);mMessageTextView = (TextView) findViewById(R.id.msg_container);mSendButton = (Button) findViewById(R.id.send);mSendButton.setOnClickListener(this);mMessageEditText = (EditText) findViewById(R.id.msg);Intent service = new Intent(this, TCPServerService.class);startService(service);new Thread() {@Overridepublic void run() {connectTCPServer();}}.start();}@Overrideprotected void onDestroy() {if (mClientSocket != null) {try {mClientSocket.shutdownInput();mClientSocket.close();} catch (IOException e) {e.printStackTrace();}}super.onDestroy();}@Overridepublic void onClick(View v) {if (v == mSendButton) {final String msg = mMessageEditText.getText().toString();if (!TextUtils.isEmpty(msg) && mPrintWriter != null) {mPrintWriter.println(msg);mMessageEditText.setText("");String time = formatDateTime(System.currentTimeMillis());final String showedMsg = "self " + time + ":" + msg + "\n";mMessageTextView.setText(mMessageTextView.getText() + showedMsg);}}}@SuppressLint("SimpleDateFormat")private String formatDateTime(long time) {return new SimpleDateFormat("(HH:mm:ss)").format(new Date(time));}private void connectTCPServer() {Socket socket = null;while (socket == null) {try {socket = new Socket("localhost", 8688);mClientSocket = socket;mPrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);mHandler.sendEmptyMessage(MESSAGE_SOCKET_CONNECTED);System.out.println("connect server success");} catch (IOException e) {SystemClock.sleep(1000);System.out.println("connect tcp server failed, retry...");}}try {// 接收服务器端的消息BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));while (!TCPClientActivity.this.isFinishing()) {String msg = br.readLine();System.out.println("receive :" + msg);if (msg != null) {String time = formatDateTime(System.currentTimeMillis());final String showedMsg = "server " + time + ":" + msg+ "\n";mHandler.obtainMessage(MESSAGE_RECEIVE_NEW_MSG, showedMsg).sendToTarget();}}System.out.println("quit...");MyUtils.close(mPrintWriter);MyUtils.close(br);socket.close();} catch (IOException e) {e.printStackTrace();}}
}

布局文件 activity_tcpclient.xml

public class TCPServerService extends Service {private boolean mIsServiceDestoryed = false;private String[] mDefinedMessages = new String[] {"你好啊,哈哈","请问你叫什么名字呀?","今天北京天气不错啊,shy","你知道吗?我可是可以和多个人同时聊天的哦","给你讲个笑话吧:据说爱笑的人运气不会太差,不知道真假。"};@Overridepublic void onCreate() {new Thread(new TcpServer()).start();super.onCreate();}@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onDestroy() {mIsServiceDestoryed = true;super.onDestroy();}private class TcpServer implements Runnable {@SuppressWarnings("resource")@Overridepublic void run() {ServerSocket serverSocket = null;try {serverSocket = new ServerSocket(8688);} catch (IOException e) {System.err.println("establish tcp server failed, port:8688");e.printStackTrace();return;}while (!mIsServiceDestoryed) {try {// 接受客户端请求final Socket client = serverSocket.accept();System.out.println("accept");new Thread() {@Overridepublic void run() {try {responseClient(client);} catch (IOException e) {e.printStackTrace();}};}.start();} catch (IOException e) {e.printStackTrace();}}}}private void responseClient(Socket client) throws IOException {// 用于接收客户端消息BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));// 用于向客户端发送消息PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);out.println("欢迎来到聊天室!");while (!mIsServiceDestoryed) {String str = in.readLine();System.out.println("msg from client:" + str);if (str == null) {break;}int i = new Random().nextInt(mDefinedMessages.length);String msg = mDefinedMessages[i];out.println(msg);System.out.println("send :" + msg);}System.out.println("client quit.");// 关闭流MyUtils.close(out);MyUtils.close(in);client.close();}}

这篇关于使用Socket实现安卓中IPC的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Git可视化管理工具(SourceTree)使用操作大全经典

《Git可视化管理工具(SourceTree)使用操作大全经典》本文详细介绍了SourceTree作为Git可视化管理工具的常用操作,包括连接远程仓库、添加SSH密钥、克隆仓库、设置默认项目目录、代码... 目录前言:连接Gitee or github,获取代码:在SourceTree中添加SSH密钥:Cl

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

windows和Linux使用命令行计算文件的MD5值

《windows和Linux使用命令行计算文件的MD5值》在Windows和Linux系统中,您可以使用命令行(终端或命令提示符)来计算文件的MD5值,文章介绍了在Windows和Linux/macO... 目录在Windows上:在linux或MACOS上:总结在Windows上:可以使用certuti

CentOS和Ubuntu系统使用shell脚本创建用户和设置密码

《CentOS和Ubuntu系统使用shell脚本创建用户和设置密码》在Linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设置密码,本文写了一个shell... 在linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

Pandas中统计汇总可视化函数plot()的使用

《Pandas中统计汇总可视化函数plot()的使用》Pandas提供了许多强大的数据处理和分析功能,其中plot()函数就是其可视化功能的一个重要组成部分,本文主要介绍了Pandas中统计汇总可视化... 目录一、plot()函数简介二、plot()函数的基本用法三、plot()函数的参数详解四、使用pl

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令