Android 学习笔记(一)(客户端、服务器socket通信教程)
来源:互联网 发布:java截最后一次出现 编辑:程序博客网 时间:2024/06/05 11:17
Android Socket通信
下面我会给大家讲解android一个简易的和服务器socket通信的例子。初学者请继续看下去...,已经会的就不要看了哈
一、服务端:
服务端我使用myeclipse建了一个项目,
源代码:
<pre name="code" class="java">package com.app.servlet;import java.io.IOException;import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket;public class MyServer{public static void main(String[] args) { try { ServerSocket server = new ServerSocket(8889); while (true) { System.out.println("服务已经启动...\n"); Socket client = server.accept(); System.out.println("接收到来自客户端的访问..\n"); OutputStream out = client.getOutputStream(); System.out.println("获取客户端消息..\n"); String msg = "机器人:欢迎你,android学院访问成功"; out.write(msg.getBytes()); System.out.println("向客户短发送响应消息..\n"); client.close(); } } catch (IOException e) { e.printStackTrace(); } } }
使用socket创建一个连接,端口未8889,server.accept()结束客户端访问,out.write(msg)将响应结果发给客户端。
二、客户端:
首先建立一个名为androiddemo的项目工程
工程树状结构图如下:
了解过android的就会知道,layout文件夹下是android的布局文件,values文件夹下是一些自定义的字符串,可以直接引用(@String就是引用的../values/string.xml)。
首先先双击layout下的activity_main.xml文件进行UI布局:
布局code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <strong><TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/portText" android:layout_alignBottom="@+id/portText" android:layout_toLeftOf="@+id/portText" android:labelFor="@+id/portText" android:text="@string/port_label" /> <Button android:id="@+id/connectButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/portText" android:layout_below="@+id/portText" android:layout_marginTop="14dp" android:onClick="btnClick" android:text="@string/button_name" /> <EditText android:id="@+id/ipText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/textView1" android:ems="10" android:text="@string/ip_address" /> <EditText android:id="@+id/portText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/ipText" android:layout_below="@+id/textView1" android:layout_marginTop="30dp" android:ems="10" android:inputType="number" android:text="@string/port_num" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/ipText" android:layout_alignBottom="@+id/ipText" android:labelFor="@+id/ipText" android:layout_alignParentLeft="true" android:layout_marginLeft="16dp" android:text="@string/server_label" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_alignRight="@+id/connectButton" android:layout_below="@+id/connectButton" android:ems="10" /></strong></RelativeLayout>
关注粗体部分。其中@string后定义的字符串在string.xml文件中。
string.xml源码:
<?xml version="1.0" encoding="utf-8"?><resources> <string name="app_name">androidDemo</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string><string name="ip_address">172.17.32.40</string><string name="server_label">服务器地址:</string><string name="port_label">端口:</string><string name="port_num">8889</string><string name="button_name">连接</string></resources>其中定义了ip_address、server_label、port_lable、port_num、button_name等字符串,可以直接使用"@string/+名称"在布局文件中引用。
android实现核心代码:
package com.example.androiddemo;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.app.Activity;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.Socket;import java.net.UnknownHostException;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class MainActivity extends Activity {private TextView myTextView;private EditText ipText;private EditText portText;private Socket socket = null;private String ip;private int port;private Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg){myTextView.setText(String.valueOf(msg.obj));}};@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);myTextView = (TextView) findViewById(R.id.textView3);ipText = (EditText) findViewById(R.id.ipText);portText = (EditText) findViewById(R.id.portText);myTextView.setText("请连接服务器!!");}// //public boolean btnClick(View v) {myTextView = (TextView) findViewById(R.id.textView3);ipText = (EditText) findViewById(R.id.ipText);portText = (EditText) findViewById(R.id.portText);ip = ipText.getText().toString();port = Integer.parseInt(portText.getText().toString());Thread th = new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {Message msg = new Message();socket = new Socket(ip, port);BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));String msgx = in.readLine();msg.obj = msgx;handler.sendMessage(msg);} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});th.start();return true;}}onCreate()方法是android主线程必须实现的代码,继承于Activity。
<span style="white-space:pre"></span>myTextView = (TextView) findViewById(R.id.textView3);ipText = (EditText) findViewById(R.id.ipText);portText = (EditText) findViewById(R.id.portText);获取xml里定义的控件。
btnClick方法是按钮”连接“的响应方法。在布局xml中定义关联
<Button
android:id="@+id/connectButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/portText"
android:layout_below="@+id/portText"
android:layout_marginTop="14dp"
android:onClick="btnClick"
android:text="@string/button_name" />
btnClick方法实现使用了handler,这是十分必要的
Thread/Handler/Looper:
很多初入Android或Java开发的新手对Thread、Looper、Handler和Message仍然比较迷惑,衍生的有HandlerThread、java.util.concurrent、Task、AsyncTask由于目前市面上的书籍等资料都没有谈到这些问题,今天就这一问题做更系统性的总结。我们创建的Service、Activity以及Broadcast均是一个主线程处理,这里我们可以理解为UI线程。但是在操作一些耗时操作时,比如I/O读写的大文件读写,数据库操作以及网络下载需要很长时间,为了不阻塞用户界面,出现ANR的响应提示窗口,这个时候我们可以考虑使用Thread线程来解决。
对于从事过J2ME开发的程序员来说Thread比较简单,直接匿名创建重写run方法,调用start方法执行即可。或者从Runnable接口继承,但对于Android平台来说UI控件都没有设计成为线程安全类型,所以需要引入一些同步的机制来使其刷新,这点Google在设计Android时倒是参考了下Win32的消息处理机制。
1. 对于线程中的刷新一个View为基类的界面,可以使用postInvalidate()方法在线程中来处理,其中还提供了一些重写方法比如postInvalidate(int left,int top,int right,int bottom) 来刷新一个矩形区域,以及延时执行,比如postInvalidateDelayed(long delayMilliseconds)或postInvalidateDelayed(long delayMilliseconds,int left,int top,int right,int bottom) 方法,其中第一个参数为毫秒
2. 当然推荐的方法是通过一个Handler来处理这些,可以在一个线程的run方法中调用handler对象的 postMessage或sendMessage方法来实现,Android程序内部维护着一个消息队列,会轮训处理这些,如果你是Win32程序员可以很好理解这些消息处理,不过相对于Android来说没有提供 PreTranslateMessage这些干涉内部的方法。
3. Looper又是什么呢? ,其实Android中每一个Thread都跟着一个Looper,Looper可以帮助Thread维护一个消息队列,但是Looper和Handler没有什么关系,我们从开源的代码可以看到Android还提供了一个Thread继承类HanderThread可以帮助我们处理,在HandlerThread对象中可以通过getLooper方法获取一个Looper对象控制句柄,我们可以将其这个Looper对象映射到一个Handler中去来实现一个线程同步机制,Looper对象的执行需要初始化Looper.prepare方法就是昨天我们看到的问题,同时推出时还要释放资源,使用Looper.release方法。
4.Message 在Android是什么呢? 对于Android中Handler可以传递一些内容,通过Bundle对象可以封装String、Integer以及Blob二进制对象,我们通过在线程中使用Handler对象的sendEmptyMessage或sendMessage方法来传递一个Bundle对象到Handler处理器。对于Handler类提供了重写方法handleMessage(Message msg) 来判断,通过msg.what来区分每条信息。将Bundle解包来实现Handler类更新UI线程中的内容实现控件的刷新操作。相关的Handler对象有关消息发送sendXXXX相关方法如下,同时还有postXXXX相关方法,这些和Win32中的道理基本一致,一个为发送后直接返回,一个为处理后才返回 .
5. java.util.concurrent对象分析,对于过去从事Java开发的程序员不会对Concurrent对象感到陌生吧,他是JDK 1.5以后新增的重要特性作为掌上设备,我们不提倡使用该类,考虑到Android为我们已经设计好的Task机制,这里不做过多的赘述,相关原因参考下面的介绍:
6. 在Android中还提供了一种有别于线程的处理方式,就是Task以及AsyncTask,从开源代码中可以看到是针对Concurrent的封装,开发人员可以方便的处理这些异步任务。
摘录自:http://www.cnblogs.com/playing/archive/2011/03/24/1993583.htm
handler机制参考: http://my.oschina.net/keeponmoving/blog/61129
点击链接触发按钮事件,发起socket请求,服务端会返回消息。
运行截图:(点击按钮之前、点击按钮之后)
http://
到此,有什么不懂的欢迎留言哈!
源代码:http://download.csdn.net/detail/lt623265189/9421360
- Android 学习笔记(一)(客户端、服务器socket通信教程)
- Android学习笔记之Socket客户端与服务端通信( 一)
- socket编程(一),实现服务器与客户端简单通信
- C# 多线程学习(三)Socket 服务器与客户端通信
- Linux服务器与JAVA客户端(android)的socket通信
- Android Socket (简单) 客户端 与服务器通信
- android客户端与服务器通信一(服务器的搭建)
- C#学习笔记-socket通信(同步,客户端+服务器,TCP)
- socket客户端服务器通信(单线程)
- socket客户端服务器通信(多线程)
- Java学习笔记(一)------服务器&客户端一对一通信小程序实现(TCP)
- Socket通信---网络通信学习笔记(一)
- Socket通信---网络通信学习笔记(一)
- IDEA搭建servlet服务器与android客户端通信(一)
- socket学习第一节:服务器和客户端通信
- Android客户端通过socket与服务器通信
- Android客户端通过socket与服务器通信
- Android客户端通过socket与服务器通信
- Simple Java—Strings and Arrays(三)为什么String被设计成了不可变型
- Error: must call SetScrollSizes() or SetScaleToFitSize()问题的解决
- iOS-如何在工程内添加pch预编译头文件
- 知识库
- hdoj 5052 Yaoge’s maximum profit 【树链剖分】
- Android 学习笔记(一)(客户端、服务器socket通信教程)
- Uva 1395
- MySQL Proxy
- pixhawk-----mavlink
- 捕获键盘中断
- <c:forEach varStatus="status">中 varStatus的属性简介
- spark transform系列__sample
- C#随机生成1到60不重复随机数
- Jenkins详细安装与构建部署使用教程