转自:http://www.devdiv.com/android_socket_-blog-258060-10594.html

一、概述

网络通信无论在手机还是其他设备上都应用得非常广泛,因此掌握网络编程是非常有必要的,而我觉得socket编程是网络编程的基础。在进入正题之前,先介 绍几点网络知识,一:socket编程有分TCP和UDP两种,TCP是基于连接的,而UDP是无连接的;二:一个TCP连接包括了输入和输出两条独立的 路径;三:服务器必须先运行然后客户端才能与它进行通信。四:客户端与服务器所使用的编码方式要相同,否则会出现乱码。下面的实现中为了讲解的方便,并没有采用多线程的方法,因此通信过程中会阻塞UI线程,而且只涉及了单向通信(客户端-->服务器),完善的程序(多线程,双向通信)会在提高篇再讲解。

二、要求

熟悉socket编程。

三、实现

新建工程MyClient,修改/res/layout/main.xml文件,在里面添加一个EditText和两个Button,完整的main.xml文件如下:

[代码]xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" > <EditText
android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入要发送的内容"
/> <Button
android:id="@+id/connectbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="连接"
/> <Button
android:id="@+id/sendbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="发送"
/> </LinearLayout>

接着,修改MyClientActivity.java文件,定义一个socket对象和一个OutputStream对象(用于发送数据),完整的内容如下:

[代码]java代码:

package com.nan.client;

 import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException; import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast; public class MyClientActivity extends Activity
{
private EditText mEditText = null;
private Button connectButton = null;
private Button sendButton = null; private Socket clientSocket = null;
private OutputStream outStream = null; /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main); mEditText = (EditText)this.findViewById(R.id.edittext);
connectButton = (Button)this.findViewById(R.id.connectbutton);
sendButton = (Button)this.findViewById(R.id.sendbutton);
sendButton.setEnabled(false); //连接按钮监听
connectButton.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View v)
{
// TODO Auto-generated method stub
try
{
//实例化对象并连接到服务器
clientSocket = new Socket("183.41.101.71",);
}
catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} displayToast("连接成功!"); connectButton.setEnabled(false);
sendButton.setEnabled(true);
}
}); //发送数据按钮监听
sendButton.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View v)
{
// TODO Auto-generated method stub
byte[] msgBuffer = null;
//获得EditTex的内容
String text = mEditText.getText().toString();
try {
//字符编码转换
msgBuffer = text.getBytes("GB2312");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} try {
//获得Socket的输出流
outStream = clientSocket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} try {
//发送数据
outStream.write(msgBuffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} displayToast("发送成功!");
}
}); } //显示Toast函数
private void displayToast(String s)
{
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
} }

接着,新建工程MyServer,同样修改/res/layout/main.xml文件,如下:

[代码]xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" > <TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="15dip" /> </LinearLayout>

修改MyServerActivity.java文件,比较简单,代码中有详细注释,如下:

[代码]java代码:

package com.nan.server;

 import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket; import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView; public class MyServerActivity extends Activity
{
private TextView mTextView = null; private InputStream mInputStream = null;
private Socket clientSocket = null;
private ServerSocket mServerSocket = null; /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main); mTextView = (TextView)this.findViewById(R.id.textview); try {
//实例化ServerSocket对象并设置端口号为8888
mServerSocket = new ServerSocket();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} try {
//等待客户端的连接(阻塞)
clientSocket = mServerSocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} try {
//获得socket的输入流
mInputStream = clientSocket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} byte[] buf = new byte[];
String str = null; try {
//读取输入的数据(阻塞读)
mInputStream.read(buf);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} try {
//字符编码转换
str = new String(buf, "GB2312").trim();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//显示接收到的数据
mTextView.setText("收到的数据:"+str); } }

最后在两个工程的AndroidMainfest.xml文件中都加入权限:

1 <uses-permission android:name="android.permission.INTERNET"></uses-permission>

到这里,客户端和服务器的程序都写好了,在模拟器上运行客户端程序:

在真机上运行服务器程序:

接着,点击客户端“连接”按钮,输入一些内容再点击“发送”按钮:

此时服务器端的情况如下:

可见成功接收了客户端发送过来的数据。

Android应用开发基础篇(12)-----Socket通信(转载)的更多相关文章

  1. Android应用开发基础篇(1)-----Button

    Android应用开发基础篇(1)-----Button   一.概述        Button,顾名思义就是按钮的意思,它主要的功能是响应用户按下按钮时的动作. 二.应用      新建一个工程, ...

  2. Android应用开发基础篇(3)-----ListView

    一.概述 ListView是一个列表显示控件,它的应用非常广泛,在很多应用程序中都可以看到它的身影,比如来电通,网易新闻等等,特别是QQ.因此非常有必要熟练掌握它. 二.要求 能够利用ListView ...

  3. Android应用开发基础篇(4)-----TabHost(选项卡)

    一.概述 TabHost是一种用来显示标签的组件,不清楚?看一下来电通这个应用就知道了.这个组件用起来与其他组件不太一样,它需要继承TabActivity这个类,还有它的布局文件与我们平时用的也有些不 ...

  4. Android应用开发基础篇(14)-----自定义标题栏

    一.概述 每一个应用程序默认的标题栏(注意与状态栏的区别)只有一行文字(新建工程时的名字),而且颜色.大小等都是固定的,给人的感觉比较单调.但当程序需要美化的时候,那么修改标题栏是就是其中一项内容,虽 ...

  5. Android应用开发基础篇(13)-----GestureDetector(手势识别)

    链接地址:http://www.cnblogs.com/lknlfy/archive/2012/03/05/2381025.html 一.概述 GestureDetector是一个用于识别手势的类,这 ...

  6. Android应用开发基础篇(9)-----SharedPreferences

    链接地址:http://www.cnblogs.com/lknlfy/archive/2012/02/27/2370319.html 一.概述 对于SharedPreferences,我吧它理解为一种 ...

  7. Android应用开发基础篇(12)-----Socket通信

    链接地址:http://www.cnblogs.com/lknlfy/archive/2012/03/03/2378669.html 一.概述 网络通信无论在手机还是其他设备上都应用得非常广泛,因此掌 ...

  8. Android应用开发基础篇(6)-----Service

    链接地址:http://www.cnblogs.com/lknlfy/archive/2012/02/20/2360336.html 一.概述 我们知道,Service是Android的四大组件之一. ...

  9. Android应用开发基础篇(2)-----Notification(状态栏通知)

    一.概述      Notification这个部件的功能是在状态栏里显示消息提醒,比如有未读的短信或者是未接的电话,那么状态栏里都会有显示,更或者是从某个应用(比如QQ,酷我音乐等等)里按Home键 ...

随机推荐

  1. xgboost调参

    The overall parameters have been divided into 3 categories by XGBoost authors: General Parameters: G ...

  2. BUPT复试专题—最值问题(2013计院)

    题目描述 给出N个数,求出这N个数中最大值和次大值.注意这里的次大值必须严格小于最大值.输入保证N个数中至少存在两个不同的数. 输入格式 第一行为测试数据的组数T(T≤20).请注意,任意两组测试数据 ...

  3. Variable 'bop' is uninitialized when captured by block

    代码: - (void)doTest { NSBlockOperation * bop = [NSBlockOperation blockOperationWithBlock:^{ if (!bop. ...

  4. CA与数字证书的自结

    1.CA CA(Certificate Authority)是数字证书认证中心的简称,是指发放数字证书.管理数字证书.废除数字证书的权威机构. 2.数字证书 如果向CA申请数字证书的单位为A.则他申请 ...

  5. [Python-MATLAB] 在Python中调用MATLAB的API

    可以参考官方的说明文档: http://cn.mathworks.com/help/matlab/matlab_external/get-started-with-matlab-engine-for- ...

  6. Service Mesh vs SideCar

    Istio = 微服务框架 + 服务治理 Istio 大幅降低微服务架构下应用程序的开发难度,势必极大的推动微服务的普及.个人乐观估计,随着isito的成熟,微服务开发领域将迎来一次颠覆性的变革.后面 ...

  7. Linux安装配置Redis CentOS 7 下安装Redis

    Redis是一个高性能的,开源key-value型数据库.是构建高性能,可扩展的Web应用的完美解决方案,可以内存存储亦可持久化存储.因为要使用跨进程,跨服务级别的数据缓存,在对比多个方案后,决定使用 ...

  8. Web 监听器

    什么事web 监听器? Servlet规范中定义的一种特殊类 用于监听ServletContext.HttpSession和ServletRequest等象的创建与销毁的事件 用监听域对象的属性发生修 ...

  9. C# 事件处理与自定义事件

    http://blog.csdn.net/cyp403/article/details/1514023 图一                                               ...

  10. setTimeout 传递的方法

    function waitExe(param){ if(time < 20){ time ++; $("#content").html(time); var self=thi ...