在 Android 中实现套接字编程



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

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

=>格拉德尔

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());
    }
}

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

在此之后:

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

加:

socket.connect()

最新更新