WebSocket WebSocket的简单用法 WebSocket的使用



                           WebSocket的使用

WebSocket一般用于局域网络的通讯使用,他比socket好用,原理也就是socket的封装,对使用者来说,比用socket更方便,快捷。


1 自定义自己的WebSocket,继承WebSocketClient,上代码:

public class WebSocketServlet extends WebSocketClient  {
private Context mContext;

public WebSocketServlet(URI serverURI,Context mContext) {
super(serverURI);
this.mContext=mContext;
}


@Override
public void onClose(int arg0, String arg1, boolean arg2) {
// TODO Auto-generated method stub
Log.e("TestWebSocketServlet", "onClose: "+arg1);

}


@Override
public void onError(Exception arg0) {
// TODO Auto-generated method stub
Log.e("TestWebSocketServlet", "onError: "+arg0.toString());
}


@Override
public void onMessage(String arg0) {
// TODO Auto-generated method stub
Log.e("TestWebSocketServlet", "onMessage: "+arg0);

Intent intent = new Intent();  
                intent.setAction("com.xiazdong");  
                intent.putExtra("name", arg0);  
                mContext.sendBroadcast(intent);  

}


@Override
public void onOpen(ServerHandshake arg0) {
// TODO Auto-generated method stub
Log.e("TestWebSocketServlet", "onOpen");
}


@Override
public void onFragment(Framedata fragment) {
// TODO Auto-generated method stub
super.onFragment(fragment);
Log.e("onFragment", "received fragment: " + new String( fragment.getPayloadData().array() ) );  
}
}



2 自己定义一个Service,在Service里面打开WebSocket,上代码

public class MTWebSocketServlet extends Service {
private String urlString = "ws://11.95.0.223:2016";
        private Context mContext;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}


@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
                mContext=MTWebSocketServlet.this;
                Log.e("MTWebSocketServlet", "on MTWebSocketServlet 启动了");
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
WebSocketServlet servlet;
try {
servlet = new WebSocketServlet(new URI(urlString),mContext);
servlet.connectBlocking();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();


}


}



以上就是核心代码了,你的websocket就写好了!

你可能感兴趣的:(Android)