Using Library:https://github.com/tavendo/autobahnandroid
package com.fkapp.websocket;import com.fkapp.websocket.r;import de.tavendo.autobahn.websocketconnection;import de.tavendo.autobahn.websocketexception;import de.tavendo.autobahn.websockethandler;import android.support.v7.app.actionbaractivity;import android.os.bundle;import android.os.handler;import android.os.message;import android.view.menu; import android.view.menuitem;import android.view.view;import android.widget.button;import Android.widget.toast;public class mainactivity extends actionbaractivity {private final StringTAG= "mainactivity";p ublic static stringwsurl= "Ws://ip:port/chat"; /* TODO: run-time replacement ip port */public websocketconnectionwsc= new Websocketconnection ();p Ublic handler handler = new handler () {@Overridepublic Void handlemessage ( Message msg ) {Super.handlemessage( msg );if ( msg.what == 0 ) {}}};p Ublic void toastlog ( string s ) {Toast.maketext ( this, s, Toast.LENGTH_SHORT ). Show ();} Private void wsstart () {Try {wsc.connect ( wsurl, new websockethandler () { @Override public void onopen () { toastlog ( "Status: connected to " + wsUrl ) wsc.sendtextmessage ( " hello, world! " ); } @Override Public void ontextmessage ( String payload ) { toastlog ( "got echo: " + payload ); } @Override public void onclose ( int code, string reason ) { toastlog ( "Connection lost. " ); } } );} catch ( WebSocketException e ) {e.printstacktrace ();}} @Overrideprotected void oncreate ( Bundle savedInstanceState ) {super.oncreate ( savedinstancestate ); Setcontentview ( R.layout.activity_main ); Wsstart (); button wssend = (Button) findviewbyid ( R.id.wsSend ); Wssend.setonclicklistener ( new view.onclicklistener () { @Override public void onclick ( View v ) { wsc.sendtextmessage ( "Ooxx" ); } } );} @Overrideprotected void ondestroy () {Super.ondestroy ();if ( wsc.isconnected () ) { Wsc.disconnect ();}} @Overridepublic boolean oncreateoptionsmenu ( Menu menu ) {/* inflate the menu; this adds items to the action bar if it is Present. */getmenuinflater (). Inflate ( R.menu.main, menu ); return (true);} @Overridepublic 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 ();if ( id == R.id.action_settings ) {return (true);} Return (super. onoptionsitemselected ( item ) );}
For communication
Android using WebSocket