Android中Socket的应用分析

本文实例分析了Android中Socket的应用。分享给大家供大家参考,具体如下:

Android 提供的常用的网络编程包括针对TCP/IP协议的Socket通信。Socket是一种跨平台的编程方式,可以在异构语言之间进行通信。

Socket程序的开发原理,是要实现服务器端和客户端。

服务器,使用ServerSocket监听指定的端口,端口可以随意指定(由于1024以下的端口通常属于保留端口,在一些操作系统中不可以随意使用,所以建议使用大于1024的端口),等待客户连接请求,客户连接后,会话产生;在完成会话后,关闭连接。

客户端,使用Socket对网络上某一个服务器的某一个端口发出连接请求,一旦连接成功,打开会话;会话完成后,关闭Socket。客户端不需要指定打开的端口,通常临时的、动态的分配一个1024以上的端口。

下面是一个实现socket的例子:

服务器端代码:

package com.socket; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; /** * com Server */ public class Main { private int ServerPort = 9999; private ServerSocket serversocket = null; private OutputStream outputStream = null; private InputStream inputStream = null; private PrintWriter printWinter = null; private Socket socket = null; private BufferedReader reader = null; public Main(){ try{ serversocket = new ServerSocket(ServerPort); System.out.println("服务启动。。。"); socket = serversocket.accept(); System.out.println("客户已连接"); }catch(Exception ex){ ex.printStackTrace(); } try{ outputStream= socket.getOutputStream(); inputStream = socket.getInputStream(); printWinter = new PrintWriter(outputStream,true); reader = new BufferedReader(new InputStreamReader(inputStream)); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true){ String message = reader.readLine(); System.out.println("client:"+message); if(message.equals("bye")||message.equals("Bye")){ break; } message = in.readLine(); printWinter.println(message); } outputStream.close(); inputStream.close(); socket.close(); serversocket.close(); System.out.print("Client is disconnected"); }catch(Exception e){ e.printStackTrace(); }finally{ } } public static void main(String[] args){ new Main(); } }

客服端代码:

package com.Aina.Android; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; 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; public class Test extends Activity implements Runnable { /** Called when the activity is first created. */ private TextView tv_msg = null; private EditText ed_msg = null; private Button btn_send = null; private Button btn_login = null; private static final String HOST = "192.168.0.132"; private static final int PORT = 9999; private Socket socket = null; private BufferedReader in = null; private PrintWriter out = null; private String content = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv_msg = (TextView) this.findViewById(R.id.TextView); ed_msg = (EditText) this.findViewById(R.id.EditText01); btn_login = (Button) this.findViewById(R.id.Button01); btn_send = (Button) this.findViewById(R.id.Button02); try { socket = new Socket(HOST, PORT); in = new BufferedReader(new InputStreamReader(socket .getInputStream())); out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); } catch (Exception ex) { ex.printStackTrace(); ShowDialog("登陆异常:" + ex.getMessage()); } btn_send.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub String msg = ed_msg.getText().toString(); if (socket.isConnected()) { if (!socket.isOutputShutdown()) { out.println(msg); } } } }); new Thread(this).start(); } public void ShowDialog(String msg) { new AlertDialog.Builder(this).setTitle("提示").setMessage(msg) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }).show(); } public void run() { try { while (true) { if(socket.isConnected()){ if(!socket.isInputShutdown()){ if ((content = in.readLine()) != null) { Log.i("TAG", "++ "+content); content += "\n"; mHandler.sendMessage(mHandler.obtainMessage()); }else{ } } } } } catch (Exception ex) { ex.printStackTrace(); } } public Handler mHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); Log.i("TAG", "-- "+msg); tv_msg.setText(tv_msg.getText().toString() + content); } }; }

XML文件布局:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/TextView" android:singleLine="false" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <EditText android:hint="content" android:id="@+id/EditText01" android:layout_width="fill_parent" android:layout_height="wrap_content"> </EditText> <Button android:text="login" android:id="@+id/Button01" android:layout_width="fill_parent" android:layout_height="wrap_content"> </Button> <Button android:text="send" android:id="@+id/Button02" android:layout_width="fill_parent" android:layout_height="wrap_content"> </Button> </LinearLayout>

先启动服务器端,再运行客户端程序。

注意:

(一)即使服务器端和客户端在一台机器上运行,也不能使用ip地址:127.0.0.1,否则,程序会出现拒绝连接的错误。

(二)客户端和服务器端最好不要建在一个工程下,最好是分别建立工程,然后启动服务器端和客户端,否则会报Error: ShouldNotReachHere()错误。这是因为Android程序不是已main方法为程序的入口。

运行效果:

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android通信方式总结》、《Android调试技巧与常见问题解决方法汇总》、《Android开发入门与进阶教程》、《Android多媒体操作技巧汇总(音频,视频,录音等)》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。

时间: 2024-08-25 06:39:40

Android中Socket的应用分析的相关文章

Android中Socket的应用分析_Android

本文实例分析了Android中Socket的应用.分享给大家供大家参考,具体如下: Android 提供的常用的网络编程包括针对TCP/IP协议的Socket通信.Socket是一种跨平台的编程方式,可以在异构语言之间进行通信. Socket程序的开发原理,是要实现服务器端和客户端. 服务器,使用ServerSocket监听指定的端口,端口可以随意指定(由于1024以下的端口通常属于保留端口,在一些操作系统中不可以随意使用,所以建议使用大于1024的端口),等待客户连接请求,客户连接后,会话产生

android 中socket通信

问题描述 android 中socket通信 private Button send; private TextView rec; private static Socket client; private boolean result=false; private int a=0; private PrintWriter write; private static BufferedReader read; public static int ac=0; private InputStream

Android中Socket通信的实现方法概述_java

本文实例简述了Android中Socket通信的实现方法,具体内容如下: 一.socket通信概述 通俗的来说套接字(socket)是通信的基石,是支持TCP/IP协议的网络通信的基本操作单元.它是网络通信过程中端点的抽象表示,包含进行网络通信必须的五种信息:连接使用的协议,本地主机的IP地址,本地进程的协议端口,远地主机的IP地址,远地进程的协议端口. 应用层通过传输层进行数据通信时,TCP会遇到同时为多个应用程序进程提供并发服务的问题.多个TCP连接或多个应用程序进程可能需要通过同一个TCP

Android中AlertDialog用法实例分析_Android

本文实例分析了Android中AlertDialog用法,分享给大家供大家参考,具体如下: Android中AlertDialog为一些程序提供了对话框,有些功能能够进一步满足程序的需要.下面举例介绍. 程序如下: import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.

Android中ImageView用法实例分析_Android

本文实例分析了Android中ImageView用法.分享给大家供大家参考,具体如下: 猜牌游戏大家可能以前都玩过,这里我们用这个小游戏来说明ImageView的用法. 首先,在res/drawable中引入三张牌:分别是梅花7,梅花8,梅花9 然后在res/layout/main.xml中配置一个TextView,三个ImageView以及一个Button <?xml version="1.0" encoding="utf-8"?> <Linea

Android中ListView用法实例分析_Android

本文实例分析了Android中ListView用法.分享给大家供大家参考,具体如下: 通过在Layout中添加ListView Widget可以达到在页面布局具有列表效果的交互页面.在这里通过举例来说明怎样在Layout中添加ListView以及怎样应用. 配合设计了两个事件Listener:  OnItemSelectedListener事件为鼠标的滚轮转动时所选择的值:OnItemClickListener事件则为当鼠标单击时,所触发的事件.由此可以区别出list中的"选择"与&q

Android中ListActivity用法实例分析_Android

本文实例分析了Android中ListActivity用法.分享给大家供大家参考,具体如下: 程序如下: import android.app.ListActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widge

Android中AlertDialog用法实例分析

本文实例分析了Android中AlertDialog用法,分享给大家供大家参考,具体如下: Android中AlertDialog为一些程序提供了对话框,有些功能能够进一步满足程序的需要.下面举例介绍. 程序如下: import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.

Android中BaseAdapter的用法分析与理解

本文实例分析了Android中BaseAdapter的用法.分享给大家供大家参考,具体如下: 最近做一个项目,项目中用到了ListView,ListView最重要的就是绑定数据,这个数据由Adapter来提供,这里我重写了BaseAdapter这个类来实现自己的menuAdapter代码如下: package org.leepood.lanorder; import java.io.InputStream; import java.util.ArrayList; import java.util