3

对不起我的英语不好。

我想在 Android 中编写一个本机应用程序来连接服务器以进行交互式通信。Websocket 技术是完美的。我已经在我的笔记本电脑上安装并运行了 Tomcat 7.0.39,IP 为 192.168.1.250。我已经尝试了示例 echo、snake 等,使用 ws://localhost:8080/.... 和使用 ws://192.168.1.250:8080/...

我正在使用带有 eclipse 的高速公路连接到我的服务器。我已经在我的 Android 手机中安装了带有高速公路客户端 websocket 示例的 apk,它与 ws://echo.websocket.org 完美连接。

问题是从 android 到我的服务器(在我的笔记本电脑中)不起作用。从 android 到 ws://echo.websocket.org 运行良好(我认为高速公路示例运行良好),我的服务器运行良好,因为 de 示例附带 tomcat 运行良好。

因为我必须对在服务器和客户端之间传输的信息进行深入的工作,所以我不能在服务器端使用 javascript,我需要 java servlet 或其他人来处理数据库、文件等等。

怎么了?防火墙已关闭,wireshark 向我展示了 android 客户端如何尝试连接到我的笔记本电脑服务器(我不太了解 wireshark 信息)但连接丢失。

这是我的安卓代码:

    package com.example.autobahnandroiddemo;

    import de.tavendo.autobahn.WebSocketConnection;
    import de.tavendo.autobahn.WebSocketException;
    import de.tavendo.autobahn.WebSocketHandler;
    import android.app.Activity;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Gravity;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;


    public class MainActivity extends Activity {

       static final String TAG = "de.tavendo.autobahn.echo";
       private static final String PREFS_NAME = "AutobahnAndroidEcho";

       static EditText mHostname;
       static EditText mPort;
       static TextView mStatusline;
       static Button mStart;

       static EditText mMessage;
       static Button mSendMessage;

       private SharedPreferences mSettings;

       private void alert(String message) {
          Toast toast = Toast.makeText(getApplicationContext(), message,         Toast.LENGTH_SHORT);
          toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
          toast.show();
       }

       private void loadPrefs() {

          mHostname.setText(mSettings.getString("hostname", ""));
          mPort.setText(mSettings.getString("port", "9000"));
       }

       private void savePrefs() {

          SharedPreferences.Editor editor = mSettings.edit();
          editor.putString("hostname", mHostname.getText().toString());
          editor.putString("port", mPort.getText().toString());
          editor.commit();
       }

       private void setButtonConnect() {
          mHostname.setEnabled(true);
          mPort.setEnabled(true);
          mStart.setText("Connect");
          mStart.setOnClickListener(new Button.OnClickListener() {
             public void onClick(View v) {
                start();
             }
          });
       }

       private void setButtonDisconnect() {
          mHostname.setEnabled(false);
          mPort.setEnabled(false);
          mStart.setText("Disconnect");
          mStart.setOnClickListener(new Button.OnClickListener() {
             public void onClick(View v) {
                mConnection.disconnect();
             }
          });
       }

       private final WebSocketConnection  mConnection = new WebSocketConnection();

       private void start() {

          final String wsuri = mHostname.getText() + ":" + mPort.getText();

          mStatusline.setText("Status: Connecting to " + wsuri + " ..");

          setButtonDisconnect();

          try {
             mConnection.connect(wsuri, new WebSocketHandler() {
                @Override
                public void onOpen() {
                   mStatusline.setText("Status: Connected to " + wsuri);
                   savePrefs();
                   mSendMessage.setEnabled(true);
                   mMessage.setEnabled(true);
                }

                @Override
                public void onTextMessage(String payload) {
                   alert("Got echo: " + payload);
                }

                @Override
                public void onClose(int code, String reason) {
                   alert("Connection lost.");
                   mStatusline.setText("Status: Ready.");
                   setButtonConnect();
                   mSendMessage.setEnabled(false);
                   mMessage.setEnabled(false);
                }
             });
          } catch (WebSocketException e) {

             Log.d(TAG, e.toString());
          }
       }

       @Override
       public void onCreate(Bundle savedInstanceState) {

          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);

          mHostname = (EditText) findViewById(R.id.hostname);
          mPort = (EditText) findViewById(R.id.port);
          mStatusline = (TextView) findViewById(R.id.statusline);
          mStart = (Button) findViewById(R.id.start);
          mMessage = (EditText) findViewById(R.id.msg);
          mSendMessage = (Button) findViewById(R.id.sendMsg);

          mSettings = getSharedPreferences(PREFS_NAME, 0);
          loadPrefs();

          setButtonConnect();
          mSendMessage.setEnabled(false);
          mMessage.setEnabled(false);

          mSendMessage.setOnClickListener(new Button.OnClickListener() {
             public void onClick(View v) {
                mConnection.sendTextMessage(mMessage.getText().toString());
             }
          });
       }

       @Override
       protected void onDestroy() {
           super.onDestroy();
           if (mConnection.isConnected()) {
              mConnection.disconnect();
           }
       }

       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
           MenuInflater inflater = getMenuInflater();
           inflater.inflate(R.menu.main_menu, menu);
           return true;
       }

       @Override
       public boolean onOptionsItemSelected(MenuItem item) {
          switch (item.getItemId()) {
             case R.id.quit:
                finish();
                break;
             default:
                return super.onOptionsItemSelected(item);
          }
          return true;
       }

    }

这是我的 SERVLET TOMCAT 代码:

    package servlets;

    import org.apache.catalina.websocket.MessageInbound;
    import org.apache.catalina.websocket.StreamInbound;
    import org.apache.catalina.websocket.WebSocketServlet;
    import org.apache.catalina.websocket.WsOutbound;

    import javax.servlet.http.HttpServletRequest;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;

    public class SimpleWebSocketServlet extends WebSocketServlet {
    private static final long serialVersionUID = 1L;

        @Override
        protected StreamInbound createWebSocketInbound(String string, HttpServletRequest hsr) {
            return new MessageInbound() {

                @Override
                protected void onBinaryMessage(ByteBuffer bb) throws IOException {

                }

                @Override
                protected void onTextMessage(CharBuffer cb) throws IOException {
                    System.out.println(cb.toString());
                    WsOutbound outbound = getWsOutbound();
                    outbound.writeTextMessage(cb);
                }
            };
        }

    }

我不知道怎么了。有另一种通过websockets将android客户端与服务器(类似技术上的java servlet)结合使用的解决方案吗?谢谢

4

1 回答 1

0

我认为您应该将连接代码放入onCreate。

于 2013-05-20T17:24:31.693 回答