android websocket client 如何调用autobahn.jar

来源:互联网 发布:java基础培训学校 编辑:程序博客网 时间:2024/06/08 05:29

       Android调用  autobahn.jar:

       1.下载源码:使用library: https://github.com/tavendo/AutobahnAndroid;

        2.编译,得到autohan.jar,拷贝到项目的lib下;

       3.MainActivity:

。。。。。。

import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketConnectionHandler;
  。。。。。。

 public class MainActivity extends Activity {

private final String      TAG = "MainActivity";

          public static String      wsUrl   = "ws://demo.lianyue.org:843"; /* TODO: 运行时替换demo.lianyue.org:843,目前这个IP是可以连通的 */

  public WebSocketConnection wsC = new WebSocketConnection();


  private void wsStart()
   {
       try {
           wsC.connect( wsUrl, new WebSocketConnectionHandler()
                    {
                        @Override
                        public void onOpen()
                        {
                                SendMessage("Status: Connected to " + wsUrl );
                       wsC.sendTextMessage( "Hello, world!" );
                        }
 
                        @Override
                        public void onTextMessage( String payload )
                        {
                            SendMessage( "Got echo: " + payload);
                  }
 
                        @Override
                        public void onClose( int code, String reason )
                        {
                       SendMessage( "Connection lost."+reason);
                     
                        }
                    } );
       } catch ( WebSocketException e ) {
           e.printStackTrace();
       }
   }

public static void SendMessage(String msg)
{

}

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

wsStart();

                wsC.sendTextMessage( "Hello, world!" );

      }

 }


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

编译后直接运行,会出现提示已连接上缺省IP:port,如果要改成自己的,注意PHP版本必须为5.3以上。


0 0
原创粉丝点击