android之socket编程实例一

本文通过Android客户端和服务器的Socket通信实例,详细解析了Socket的实现原理,并提供了完整的客户端和服务端代码实现,帮助开发者深入理解Socket通信过程。

    Socket本质上就是Java封装了传输层上的TCP协议,所以要想知道它的实现原理,建议去看java的api帮助文档了,这里我就不一一介绍了!下面,我用一个实例给大家说明一下吧。

--------------客户端项目代码------------------------

新建一个Android项目工程SimpleSocket

main_activity.xml文件代码入下:

<?xml version="1.0" encoding="utf-8"?>
<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">

    <EditText
        android:id="@+id/ed1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="给服务器发送信息" />

    <Button
        android:id="@+id/send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/ed1"
        android:text="发送" />

    <TextView
        android:id="@+id/txt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/send"
        android:textSize="15sp" />
</RelativeLayout>

MainActivity.java的代码如下:

package com.yaowen.simpelsocket;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class MainActivity extends AppCompatActivity {

    Socket socket = null;
    String buffer = "";
    TextView textView;
    Button send;
    EditText editText;
    String strClientText;
    public Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x11) {
                Bundle bundle = msg.getData();
                textView.append("server:" + bundle.getString("msg") + "\n");
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.txt1);
        send = (Button) findViewById(R.id.send);
        editText = (EditText) findViewById(R.id.ed1);
        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                strClientText = editText.getText().toString();
                textView.append("client:" + strClientText + "\n");
                //启动线程 向服务器发送和接收信息
                new MyThread(strClientText+"\n").start();
            }
        });

    }

    class MyThread extends Thread {

        public String string;

        public MyThread(String string) {
            this.string = string;
        }

        @Override
        public void run() {
            //定义消息
            Message msg = new Message();
            msg.what = 0x11;
            Bundle bundle = new Bundle();
            bundle.clear();
            try {
                //连接服务器 并设置连接超时为5秒
                socket = new Socket();
                socket.connect(new InetSocketAddress("192.168.3.200", 30000), 5000);
                //获取输入输出流
                OutputStream ou = socket.getOutputStream();
                BufferedReader bff = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                //读取发来服务器信息
                String line = null;
                buffer = "";
                while ((line = bff.readLine()) != null) {
                    buffer = line + buffer;
                }

                //向服务器发送信息
                ou.write((strClientText + ";").getBytes("gbk"));
                ou.flush();
                bundle.putString("msg", buffer.toString());
                msg.setData(bundle);
                //发送消息 修改UI线程中的组件
                myHandler.sendMessage(msg);
                //关闭各种输入输出流
                bff.close();
                ou.close();
                socket.close();
            } catch (SocketTimeoutException aa) {
                //连接超时 在UI界面显示消息
                bundle.putString("msg", "服务器连接失败!请检查网络是否打开");
                msg.setData(bundle);
                //发送消息 修改UI线程中的组件
                myHandler.sendMessage(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

最后别忘了在mainfests文件里添加访问网络权限,否则会抛异常!

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

-------------服务器代码------------------------------

新建一个java项目,如:net

新建一个AndroidService类,代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class AndroidRunable implements Runnable {
 Socket socket = null;
 public AndroidRunable(Socket socket) {
  this.socket = socket;
 }
 @Override
 public void run() {
  // 向android客户端输出hello worild
  String line = null;
  InputStream input;
  OutputStream output;
  String str = "hello world!";
  try {
   // 向客户端发送信息
   output = socket.getOutputStream();
   input = socket.getInputStream();
   BufferedReader bff = new BufferedReader(
     new InputStreamReader(input));
   output.write(str.getBytes("gbk"));
   output.flush();
   // 关闭socket
   socket.shutdownOutput();
   // 获取客户端的信息
   while ((line = bff.readLine()) != null) {
    System.out.print(line);
   }
   // 关闭输入输出流
   output.close();
   bff.close();
   input.close();
   socket.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

再新建一个AndroidRunable的类,继承与Runnable类,代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class AndroidRunable implements Runnable {
 Socket socket = null;
 public AndroidRunable(Socket socket) {
  this.socket = socket;
 }
 @Override
 public void run() {
  // 向android客户端输出hello worild
  String line = null;
  InputStream input;
  OutputStream output;
  String str = "hello world!";
  try {
   // 向客户端发送信息
   output = socket.getOutputStream();
   input = socket.getInputStream();
   BufferedReader bff = new BufferedReader(
     new InputStreamReader(input));
   output.write(str.getBytes("gbk"));
   output.flush();
   // 关闭socket
   socket.shutdownOutput();
   // 获取客户端的信息
   while ((line = bff.readLine()) != null) {
    System.out.print(line);
   }
   // 关闭输入输出流
   output.close();
   bff.close();
   input.close();
   socket.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

就这样子,服务器代码也编写完了,接下来运行服务代码,再把Android的项目跑起来,下面是这个例子的最终效果图:

1】服务器的运行状态:

172247_mOUg_2391602.png

2】客户端的运行状态:

 

172248_fpyB_2391602.png

注意:由上面的图片可知,我是用真机调试的,所以,真机要和启动服务的设备处在同一局域网才可以跑!

 

 

转载于:https://my.oschina.net/yaowen424/blog/527456

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值