在Android中实现套接字编程

时间:2017-11-09 10:14:41

标签: android sockets socket.io

Socket.io给出错误 SocketIOException:握手时出错, 我该如何解决它。在我的gradle文件中。我想开发一个仅适用于socket连接的app。

如果存在任何其他库,请向我推荐我可以轻松集成到我的应用程序中。

=>摇篮

compile ('io.socket:socket.io-client:0.9.0') {
    // excluding org.json which is provided by Android
    exclude group: 'org.json', module: 'json'
}

=>主要活动

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.MalformedURLException;


import netsol.app.socketioexample.SocketUtils.IOAcknowledge;
import netsol.app.socketioexample.SocketUtils.IOCallback;
import netsol.app.socketioexample.SocketUtils.SocketIO;
import netsol.app.socketioexample.SocketUtils.SocketIOException;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        socketStart();
    }

    SocketIO socket = null;
    private void socketStart() {

        try {
            socket = new SocketIO("http://xxx.xxx.x.23:808");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        socket.connect(new IOCallback() {
            @Override
            public void onMessage(JSONObject json, IOAcknowledge ack) {
                try {
                    System.out.println("Server said:" + json.toString(2));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onMessage(String data, IOAcknowledge ack) {
                System.out.println("Server said: " + data);
            }

            @Override
            public void onError(SocketIOException socketIOException) {
                System.out.println("an Error occured");
                socketIOException.printStackTrace();
            }

            @Override
            public void onDisconnect() {
                System.out.println("Connection terminated.");
            }

            @Override
            public void onConnect() {
                System.out.println("Connection established");
            }

            @Override
            public void on(String event, IOAcknowledge ack, Object... args) {
                System.out.println("Server triggered event '" + event + "'");
            }


        });

        // This line is cached until the connection is establisched.
        socket.send("Hello Server!");
    }

    public void send_click(View view) {
        socket.send(((TextView) findViewById(R.id.txt_test)).getText().toString());
    }
}

1 个答案:

答案 0 :(得分:0)

您正在实施方法,但您还必须与服务器建立连接。 您没有连接插座

之后:

socket = new SocketIO("http://192.168.2.23:808");

添加:

socket.connect()