android实现socket端口通信demo

本文介绍了Android中如何实现Socket通信,对比了Socket与HTTP通信的区别,并强调Socket的主动推送特性。通过创建Socket连接,实现数据高效、低丢失率的传输。在Android应用中,需要在manifest文件中添加INTERNET权限以确保网络访问。

android实现socket端口通信demo

(1)socket通信描述

Android与服务器的通信方式主要有两种,一是Http通信,一是Socket通信。两者的最大差异在于,http连接使
用的是“请求—响应方式”,即在请求时建立连接通道,当客户端向服务器发送请求后,服务器端才能向客户端
返回数据。而Socket通信则是在双方建立起连接后就可以直接进行数据的传输,在连接时可实现信息的主动推送
,而不需要每次由客户端想服务器发送请求。 那么,什么是socket?Socket又称套接字,在程序内部提供了与
外界通信的端口,即端口通信。通过建立socket连接,可为通信双方的数据传输传提供通道。socket的主要特点
有数据丢失率低,使用简单且易于移植。
TCP使用的是流的方式发送,UDP是以包的形式发送。

(2)android端

public class MainActivity extends ActionBarActivity implements View.OnClickListener {
    private EditText editText;
    private TextView textView;

    private Socket socket;
    private String buffer = "";

    public Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1314){
                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);

        editText = (EditText) findViewById(R.id.editText);
        textView = (TextView) findViewById(R.id.textView);
        findViewById(R.id.button).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                String edtext = editText.getText().toString().trim();
                if (TextUtils.isEmpty(edtext)){
                    Toast.makeText(this,"内容不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                textView.append("client:" + edtext + "\n");
                editText.setText("");

                new SocketThread(edtext).start();
                break;
        }
    }

    class SocketThread extends Thread {
        public String sendtext;
        public SocketThread(String txt) {
            this.sendtext = txt;
        }

        @Override
        public void run() {
            //定义消息
            Message msg = new Message();
            msg.what = 1314;
            Bundle bundle = new Bundle();
            bundle.clear();
            try {
                Log.e("chenzhongzhi","--1--");
                //连接服务器,设置连接超时为5秒
                socket = new Socket();
                socket.connect(new InetSocketAddress("192.168.1.42", 29999), 5000);
                Log.e("chenzhongzhi","--2--");
                //获取流
                OutputStream os = socket.getOutputStream();
                BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                Log.e("chenzhongzhi","--3--");
                //读取服务器发来消息
                String line = null;
                buffer = "";
                Log.e("chenzhongzhi","--4--");
                while ((line = bff.readLine()) != null){
                    buffer = line + buffer;
                }
                Log.e("chenzhongzhi","--5--");
                //向服务器发送消息
                os.write(sendtext.getBytes("gbk"));
                os.flush();
                Log.e("chenzhongzhi","--6--");
                bundle.putString("msg",buffer.toString());
                msg.setData(bundle);
                //发送消息修改textview
                mHandler.sendMessage(msg);
                Log.e("chenzhongzhi","--7--");
                //关闭流
                try {
                    bff.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
                try {
                    os.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
                try {
                    socket.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            } catch (IOException e) {
                //连接超时
                bundle.putString("msg","服务器连接失败");
                msg.setData(bundle);
                mHandler.sendMessage(msg);
                e.printStackTrace();
            }
        }
    }
}

<LinearLayout 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:orientation="vertical"
    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/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text=".................." />
</LinearLayout>

(4)服务端

public class AndroidRunable implements Runnable{
	
	Socket socket = null;
	public AndroidRunable(Socket socket) {
		super();
		this.socket = socket;
	}

	@Override
	public void run() {
		String line = null;
		InputStream in = null;
		OutputStream out = null;
		String str = "czz fydsw 1314";
		try {
			out = socket.getOutputStream();
			in = socket.getInputStream();
			BufferedReader bff = new BufferedReader(new InputStreamReader(in));
			out.write(str.getBytes("gbk"));
			out.flush();
			socket.shutdownOutput();
			while((line = bff.readLine()) != null){
				System.out.println(line);
			}
			//关闭流
            try {
                out.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            try {
                bff.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            try {
                in.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            try {
                socket.close();
            }catch (Exception e){
                e.printStackTrace();
            }
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}

public class AndroidService {
	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(29999); 
		while(true){
			Socket socket = server.accept();
			new Thread(new AndroidRunable(socket)).start();
		}
	}
}

(5)注意点

1.androidManifest添加网络权限

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

2.android端与服务器端的socket端口一致






评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值