「Efficient Android Threading 笔记」- C1 Android Components and the Need for Multiprocessing Android RecyclerView Android Socket Programming Supporting Multiple Screens Make a Reusable UI in Android App Development 如何在 Android Studio 中包含 *.so library,并使用库中定义的方法? 使用 SpannableString 格式化字符串,实现前景色、下划线、超链接、图文混排等 如何使用 bound service 完成进程间通信? 创建自定义视图 Creating custom views 通过 Android Theme & Style 定制应用的样式 「译」Android ViewPropertyAnimator 介绍 Android Animation Interpolator - Android 动画插值器源码笔记 「译」Android Animation in Honeycomb by Chet Haase(Android 3.0系统中的动画机制) 从 Android Sample ApiDemos 中学习 android.animation API 的用法 如何学习 Android Animation? 如何实现 Android ListView「上拉加载更多」? 「译」向Big Nerd Ranch提问:为什么Fragment在Android App开发中非常重要? 分类整理我在 SegmentFault 上针对某些问题作的回答 Android Servcie 后台服务总结笔记 如何在Android设备旋转时暂存数据以保护当前的交互状态? Android Message Handler 消息处理机制总结笔记 如何获取FragmentTabHost中指定标签页的Fragment? Fragment子类必须包含一个public无参构造器 如何更新及替换ViewPager中的Fragment? 如何使用Android UI Fragment开发“列表-详情”界面? 一个Android音频文本同步的英文有声读物App的开发过程 「Android编程权威指南笔记」Android应用本地化 通过jfeinstein10/SlidingMenu实现Android侧滑菜单 为Ubuntu14.04部署Android App的Eclipse开发环境 「Android编程权威指南笔记」使用ListFragment显示列表 「Android编程权威指南笔记」SDK版本与兼容 「Android编程权威指南笔记」Android布局和组件 「Android编程权威指南笔记」UI Fragment 「Android编程权威指南笔记」Activity 第一次开发iOS App和Android的对比总结笔记 「App Training笔记」创建第一个应用 「App Training笔记」开发入门训练大纲 Android APP - 从远程FTP服务器下载文件到本地

Android Socket Programming

2017年02月04日

文章链接:http://li2.me/2017/02/android-socket-programming.html

ClientSocket

An Android App which implements the client-side socket.

NetworkConnection is a class designed to manage the socket connection:

// @author: weiyi.li, http://li2.me
public class NetworkConnection {
    /*
     * A boolean flag to record connection status. When connection status changed,
     * et: open/close socket, network disconnect,
     * the flag will be updated and the callback will be invoked to notify UI.
     */
    private boolean mIsConnected;
    
    /** A callback for UI to update */
    public interface ConnectionListener {
        void onConnected(final boolean isConnected, final String disconnectReason);
        void onDataReceived(final String data);
        void onDataSent(final String data, final boolean succeeded);
    }

    /** Constructor */
    public NetworkConnection(Context context, ConnectionListener listener) {}

    /** Connect to server */
    public void connect(final String serverIp, final int serverPort) {}

    /** Disconnect to server */
    public void disconnect(final String disconnectReason) {}
    
    /** Send data to server */
    public void sendData(final String data) {}
    
    public boolean isConnected() {}
    
    /** Receive data from server through a thread when connected */
    private void startReceiveThread() {
        ...
            public void run() {
                try {
                    while (isConnected() && !mReceiveThreadInterrupted) {
                        mDataInputStream.readUTF();
                    }
                } catch (IOException e) {
                    // consider as disconnection to server
                }
            }
        ...
    }
}

Through this class, UI don’t need to care about the details of connection (socket, input/output stream), just register the callback and use the public method to connect/disconnect/send data to server. commit #2f452ea

// @author: weiyi.li, http://li2.me
public class MainActivity extends AppCompatActivity {
    private NetworkConnection mConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Create connection
        mConnection = new NetworkConnection(this, mConnectionListener);
    }

    @Override
    protected void onDestroy() {
        // Destroy connection
        if (mConnection != null)
        {
            mConnection.disconnect("MainActivity.onDestroy");
        }
    }

    @OnClick(R.id.connectBtn)
    void connectToServer() {
        if (!mConnection.isConnected()) {
            mConnection.connect(ip, port);
        } else {
            mConnection.disconnect("User intent to disconnect");
        }
    }

    @OnClick(R.id.sendBtn)
    void sendToServer(String data) {
        if (mConnection.isConnected()) {
            mConnection.sendData(data);
        }
    }

    private NetworkConnection.ConnectionListener mConnectionListener =
        new NetworkConnection.ConnectionListener() {
            @Override
            public void onConnected(boolean isConnected, String disconnectReason) {
                Log.d(TAG, "onConnected " + isConnected);
            }

            @Override
            public void onDataReceived(String data) {
                Log.d(TAG, "onDataReceived " + data);
            }

            @Override
            public void onDataSent(String data, boolean succeeded) {}
        };
}

ServerSocket

A Java Project which implements the server-side socket. When server is running, it waits new client connection, receive data from client, send response to this client, and broadcast the data to other clients. To run the server:

$ ./runServer.sh

To support multiple clients socket connection, create a thread pool (through ExecutorService), commit #aac37a0.

References

Demo Figures

Server

Client1

book-cover


weiyi.li, 2017-01-14, http://li2.me


知识共享许可协议
li2的博客WeiYi.Li 创作,采用 知识共享 署名-非商业性使用 4.0 国际 许可协议进行许可。
© 2011-2017. All rights reserved by WeiYi.Li. Powerd by Jekyll & LinAnYa's Theme