Android SocketClient库的使用

Posted 鹏于宴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android SocketClient库的使用相关的知识,希望对你有一定的参考价值。

1.在app目录下的build.gradle里配置:

implementation 'com.github.vilyever:androidSocketClient:2.0.1'

2.在根目录下的settings.gradle里配置:

jcenter()
maven  url "https://www.jitpack.io'

3.添加权限:

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

4.传入服务器地址获取IP:

/**
* 解析域名获取IP数组
* @param host
* @return
*/
public void getIp(final String host) 
        new Thread(new Runnable() 
            @Override
            public void run() 
                
                try 
                    String[] ipAddressArr = null;
					InetAddress[] inetAddressArr = InetAddress.getAllByName(host);
                    if (inetAddressArr != null && inetAddressArr.length > 0) 
                        ipAddressArr = new String[inetAddressArr.length];
                        for (int i = 0; i < inetAddressArr.length; i++) 
						ipAddressArr[i] = inetAddressArr[i].getHostAddress();
                            Log.i("myipurl", i + "---" + ipAddressArr[i]);  					  
                            if (ipAddressArr[i] != null || !ipAddressArr[i].equals("null")) 
                                MySave.getInstance().saveShare("myIp", ipAddressArr[i]);
                                Log.i("myipurl", "ipAddressArr------:" + ipAddressArr[i]);   
                              
                        
					
                 catch (UnknownHostException e) 
                    e.printStackTrace();
                

            
        ).start();

    

4.主代码:

public class MainActivity extends AppCompatActivity 
    private SocketClient socketClient;
    private SocketClientDelegate delegate;
    private EditText et_text;
    private Button btn_send;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_text = (EditText) findViewById(R.id.et_text);
        btn_send = (Button) findViewById(R.id.btn_send);
        try 
            startSocketClient("");
         catch (IOException e) 
            e.printStackTrace();
        
 
        btn_send.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                String string = et_text.getText().toString().trim();
                if (!TextUtils.isEmpty(string))
                    socketSendMessage(string);
                    et_text.setText("");
                
 
            
        );
    
 
    //socket通信
    private void startSocketClient() throws IOException 
    
       socketClient = new SocketClient();
        //socketClient.getAddress().setRemoteIP(array[0]);//设置IP,这里设置的是本地IP
        //socketClient.getAddress().setRemotePort(String.valueOf(Integer.parseInt(array[1])));//设置端口
        socketClient.getAddress().setRemoteIP("49.4.69.20");//设置IP,这里设置的是本地IP
        socketClient.getAddress().setRemotePort(16018);//设置端口
        socketClient.getAddress().setConnectionTimeout(15 * 1000);//设置超时时间
 
        //socketClient.setCharsetName(CharsetUtil.UTF_8);//设置编码格式,默认为UTF-8
        socketClient.setCharsetName("GBK");//设置编码格式,默认为UTF-8
        socketClient.connect(); // 连接,异步进行
 
        //常用回调配置
        // 对应removeSocketClientDelegate
        socketClient.registerSocketClientDelegate(delegate = new SocketClientDelegate() 
            /**
             * 连接上远程端时的回调
             */
            @Override
            public void onConnected(SocketClient client) 
                Log.d("melog", "gamesocket连接成功");
                //launcher.callExternalInterface("gameSocketConnectSuccess", "success");
            
 
            /**
             * 与远程端断开连接时的回调
             */
            @Override
            public void onDisconnected(SocketClient client) 
                Log.d("melog", "gamesocket连接断开");
                // 可在此实现自动重连
                 socketClient.connect();
                //launcher.callExternalInterface("socketClose", "close");
            
 
            /**
             * 接收到数据包时的回调
             */
            @Override
            public void onResponse(SocketClient client, @NonNull SocketResponsePacket responsePacket) 
 
                String message = responsePacket.getMessage(); // 获取按默认设置的编码转化的String,可能为null
                Log.i("接收服务端消息:",message);
 
                //launcher.callExternalInterface("socketDataHandler", message);
            
        );
    
 
    //发送消息
    private void socketSendMessage(String info) 
        String status = String.valueOf(socketClient.getState());
        if (socketClient != null && status == "Connected") 
            socketClient.sendData(info.getBytes()); // 发送byte[]消息
        
    
 
    //前台请求gamesocket连接状态
    private void requestGameSocketConnectFlg() 
        String status = String.valueOf(socketClient.getState());
        //launcher.callExternalInterface("gameSocketFlg", status);
    
 
    //前台主动断开gamesocket
    private void closeGameSocket() 
        if (socketClient != null) 
            socketClient.removeSocketClientDelegate(delegate);
            socketClient.disconnect();
        
    

以上是关于Android SocketClient库的使用的主要内容,如果未能解决你的问题,请参考以下文章

封装socketclient动态链接库

如何使用wifi直接将套接字与android连接

Android Java ServerSocket 端口号不是它应该是的

使用带有内部库的 maven 构建 android 项目

Android Material Design 兼容库的使用

使用 smack 库的 android 头像管理