Android socket通信app Client端

作者: houlucky | 来源:发表于2016-03-24 21:41 被阅读1782次

MainActivity.java

package com.houxy.chat;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener{
    private EditText editIP;
    private EditText editPort;
    private EditText editMsg;
    private Button btnLink;
    private Button btnSend;
    private TextView textReceive;

    private Handler mHandler = new Handler(Looper.getMainLooper());
    private TcpClient tcpClient = new TcpClient() {
        @Override
        public void onConnect() {
            refreshUI(true);
        }

        @Override
        public void onConnectBreak() {
            refreshUI(false);
        }

        @Override
        public void onReceive(final String s) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    textReceive.append("server:" + s + "\n\n");
                }
            });
        }

        @Override
        public void onConnectFalied() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "连接失败",
                             Toast.LENGTH_LONG);
                }
            });
        }

        @Override
        public void onSendSuccess(final String s) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    textReceive.append("我:" + s + "\n\n");
                }
            });
        }


    };

    private void refreshUI(final boolean isConnected) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                editIP.setEnabled(!isConnected);
                editPort.setEnabled(!isConnected);
                btnLink.setText(isConnected  ? "断开" : "连接");
                btnSend.setBackgroundResource(isConnected ?
                       R.drawable.send_button : R.drawable.send_button_disabled );
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        refreshUI(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_Link:
                if(tcpClient.isConnected()){
                    tcpClient.disConnected();
                }else {
                    String IP = editIP.getText().toString().trim();
                    String strPort = editPort.getText().toString();
                    int port = Integer.parseInt(strPort);
                    tcpClient.connect(IP, port);
                }
                break;
            case R.id.btn_sendMsg:
                String msg = editMsg.getText().toString();
                editMsg.setText("");
                tcpClient.getTransceiver().sendMSG(msg);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onStop() {
        tcpClient.disConnected();
        super.onStop();
    }

    private void initView() {
        setContentView(R.layout.activity_main);
        editIP = (EditText)findViewById(R.id.ed_ip);
        editPort = (EditText)findViewById(R.id.ed_port);
        editMsg = (EditText)findViewById(R.id.edit_msg);
        btnLink = (Button)findViewById(R.id.btn_Link);
        btnSend = (Button)findViewById(R.id.btn_sendMsg);
        textReceive = (TextView)findViewById(R.id.tx_receive);
       // listView = (ListView)findViewById(R.id.listView);
        btnSend.setOnClickListener(this);
        btnLink.setOnClickListener(this);
    }
}

TcpClient.java

  • TcpClient 是Tcp Socket客户端的程序,主要是实现socket的连接,并利用SocketTransceiver进行数据的收发工作
  • 这里对几个抽象函数特别介绍一下
public abstract void onConnect();  
//当socket成功连接的时候回调此函数刷新UI界面
public abstract void onConnectBreak();  
//当连接意外断开的时候回调此函数
public abstract void onReceive(String s);  
//当收到服务器端发送回来的数据时,回调此函数,显示聊天数据在UI界面
public abstract void onConnectFalied();  
//开始连接未完成,抛出异常时回调此函数
public abstract void onSendSuccess(String s);   
//当socket 服务器端接收到数据后将发送的数据显示在客户端界面
package com.houxy.chat;

import android.util.Log;
import java.io.IOException;
import java.net.Socket;

/**
 * Created by asus on 2016/3/23.
 */
public abstract class TcpClient implements Runnable{

    private  String IP;
    private int port;
    boolean connect = false;
    private SocketTransceiver transceiver;
    private Socket socket;
    public void connect(String IP, int port){
        this.IP = IP;
        this.port = port;
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
                transceiver = new SocketTransceiver() {
                @Override
                public void onReceive(String s) {
                    TcpClient.this.onReceive(s);
                }

                @Override
                public void onConnectBreak() {
                    TcpClient.this.onConnectBreak();
                }

                    @Override
                    public void onSendSuccess(String s) {
                        TcpClient.this.onSendSuccess(s);
                    }


                };
                socket = new Socket(IP, port);
                connect = true;
            Log.d("connect", String.valueOf(connect));
                this.onConnect();
                transceiver.start(socket);
        } catch (IOException e) {
            this.onConnectFalied();
            e.printStackTrace();
        }
    }

    protected  boolean isConnected(){
        return connect;
    }

    public void disConnected(){
        connect = false;
        if(transceiver!=null){
            transceiver.stop();
            transceiver=null;
        }
    }

    public SocketTransceiver getTransceiver(){
        return transceiver;
    }

    public abstract void onConnect();

    public abstract void onConnectBreak();

    public abstract void onReceive(String s);

    public abstract void onConnectFalied();

    public abstract void  onSendSuccess(String s);

}

SocketTransceiver.java

  • 此类主要是进行数据的收发
  • 这里的几个抽象方法同上
package com.houxy.chat;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
 * Created by asus on 2016/3/23.
 */
public abstract class SocketTransceiver implements Runnable{

    private Socket socket;
    private DataInputStream dataInputStream;
    private DataOutputStream dataOutputStream;
    private InputStream inputStream;
    private OutputStream outputStream;
    private boolean runFlag = false;

    public void start(Socket socket){
        this.socket = socket;
        runFlag = true;
        new Thread(this).start();
    }

    public void stop(){
        runFlag = false;
        try {
            socket.shutdownInput();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
        } catch (IOException e) {
            runFlag = false;
            e.printStackTrace();
        }

        while (runFlag){
  //线程死循环  不停的从服务器端读回数据,并通过onReceiver()方法回传显示到UI
            dataInputStream = new DataInputStream(inputStream);
            try {
                String s = dataInputStream.readUTF();
                this.onReceive(s);
            } catch (IOException e) {

                runFlag = false;
                e.printStackTrace();
            }
        }

        //断开连接
        try {
            inputStream.close();
            outputStream.close();
            socket.close();
            dataInputStream.close();
            if (dataOutputStream != null)
                dataOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.onConnectBreak();//连接被动断开
    }

    public void sendMSG(String s){
        if( outputStream != null){
            dataOutputStream = new DataOutputStream(outputStream);
            try {
                dataOutputStream.writeUTF(s);
                dataOutputStream.flush();
                this.onSendSuccess(s);
            } catch (IOException e) {
                onConnectBreak();
                runFlag = false;
                e.printStackTrace();
            }
        }

    }

    public abstract void onReceive(String s);

    public abstract void onConnectBreak();

    public abstract void onSendSuccess(String s);

}

  • 注意在安卓权限中加入网络权限

      <uses-permission android:name="android.permission.INTERNET"/>
    
  • Client端截图

2016-03-24_223256.png

相关文章

网友评论

  • justread:再Android studio中服务端的sockey这在哪里呢
    houlucky:@怀抱自信 http://blog.csdn.net/defonds/article/details/7971259
    http://www.paincker.com/java-tcp-socket
    这两篇文章不错
    369a93e7e7df:你好?我对socket不是很了解,请问有没有demo,我想学习一下,谢谢
    houlucky:那个还有一篇文章是关于server端的

本文标题:Android socket通信app Client端

本文链接:https://www.haomeiwen.com/subject/ufurlttx.html