首页 > 代码库 > Android使用websocket
Android使用websocket
使用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 String TAG = "MainActivity"; public static String wsUrl = "ws://ip:port/chat"; /* TODO: 运行时替换ip port */ public WebSocketConnection wsC = new WebSocketConnection(); public Handler handler = new Handler() { @Override public void handleMessage( Message msg ) { super.handleMessage( msg ); if ( msg.what == 0 ) { } } }; public 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(); } } @Override protected 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" ); } } ); } @Override protected void onDestroy() { super.onDestroy(); if ( wsC.isConnected() ) { wsC.disconnect(); } } @Override public 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); } @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(); if ( id == R.id.action_settings ) { return(true); } return(super.onOptionsItemSelected( item ) ); } }
进行通信
Android使用websocket
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。