Java - 无法连接到Websocket

时间:2016-06-17 13:17:58

标签: java android websocket

所以我最终最终与JAVA合作,并尝试与Websocket建立联系。

我过去常常通过Javascript进行连接,但这有点不同; - )

我已经按照Anders Carlsson link

的教程进行了操作

但是,在Android Studio中运行应用程序时,在创建Websocket对象时出现以下错误:

E/AndroidRuntime: FATAL EXCEPTION: main                                                             
     Process: com.example.eglu.test, PID: 23459
     java.lang.NoClassDefFoundError: com.example.eglu.test.MainActivity$2
        at com.example.eglu.test.MainActivity.connectWebSocket(MainActivity.java:86)
        at com.example.eglu.test.MainActivity.onCreate(MainActivity.java:44)
        at android.app.Activity.performCreate(Activity.java:6237)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)


由于我对JAVA很陌生,我很难弄清楚哪些文件与你们相关,所以如果你需要我的东西,请告诉我们。

在我的 build.gradle 中,我已经获得了这些dependencies

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile "org.java-websocket:Java-WebSocket:1.3.0"
}


我在 AndroidManifest.xml 中的活动如下所示

   <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <uses-permission android:name="android.permission.INTERNET" />
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


我项目中的 MainActivity.java 文件

  package com.example.eglu.test;

  import android.os.Build;
  import android.os.Bundle;
  import android.support.design.widget.FloatingActionButton;
  import android.support.design.widget.Snackbar;
  import android.support.v7.app.AppCompatActivity;
  import android.support.v7.widget.Toolbar;
  import android.util.Log;
  import android.view.View;
  import android.view.Menu;
  import android.view.MenuItem;
  import android.webkit.ConsoleMessage;
  import android.widget.EditText;

  import org.java_websocket.client.WebSocketClient;
  import org.java_websocket.handshake.ServerHandshake;

  import java.net.URI;
  import java.net.URISyntaxException;
  import java.util.UUID;

  public class MainActivity extends AppCompatActivity {
        private WebSocketClient mWebSocketClient;
        public final static String EXTRA_MESSAGE = "com.example.eglu.text.MESSAGE";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null)
                    .show();
        }
    });

    connectWebSocket();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/** Called when the user clicks the "Send" button **/
public void sendMessage(View view){
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    if(message.length() > 0){
        mWebSocketClient.send(message);
        editText.setText("");
    }
}

private void connectWebSocket() {
    URI uri;
    try {
        uri = new URI("ws://192.168.1.163:8080");
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return;
    }

    System.out.println("Websocket URI : " + uri);

    mWebSocketClient = new WebSocketClient(uri) {
        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            Log.i("Websocket", "Opened");

            String message = "{" +
                    "\"Request\":\"INIT\"," +
                    "\"Respond\": " + UUID.randomUUID() + "," +
                    "\"Payload\": {}" +
                    "}";

            mWebSocketClient.send(message);
        }

        @Override
        public void onMessage(String s) {
            final String message = s;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    EditText editText = (EditText) findViewById(R.id.edit_message);
                    editText.setText(editText.getText() + "\n" + message);
                }
            });
        }

        @Override
        public void onClose(int i, String s, boolean b) {
            Log.i("Websocket", "Closed " + s);
        }

        @Override
        public void onError(Exception e) {
            Log.i("Websocket", "Error " + e.getMessage());
        }
    };
    mWebSocketClient.connect();
}
}

0 个答案:

没有答案