1. 程式人生 > >android利用websocket協議與伺服器通訊

android利用websocket協議與伺服器通訊

最近做一個專案,需求中需要伺服器主動推送訊息到客戶端。這樣的話一般的http連線就不能使用了。博主問了個朋友,向我推薦websocket協議,特此測試了一下,發現效果很好。

客戶端程式碼。。。。

介面佈局自己寫,很簡單的兩個button

package com.example.test;

import com.example.test.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketConnectionHandler;
import de.tavendo.autobahn.WebSocketException;

public class MainActivity extends Activity implements OnClickListener {

	private Button bt;
	private EditText ed_name;
	private EditText ed_text;
	private Button bt1;
	WebSocketConnection wsc;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		bt = (Button) findViewById(R.id.bt);
		ed_name = (EditText) findViewById(R.id.ed_name);
		ed_text = (EditText) findViewById(R.id.ed_text);
		bt1 = (Button) findViewById(R.id.bt1);
		bt.setOnClickListener(this);
		bt1.setOnClickListener(this);
		wsc = new WebSocketConnection();

	}

	private void connect() {
		System.out.println("開始連線websocket///");

		try {

			wsc.connect("ws://192.168.1.245:8080/DriveServer/mainservlet",
					new WebSocketConnectionHandler() {
				
						@Override
						public void onBinaryMessage(byte[] payload) {
							System.out.println("onBinaryMessage size="
									+ payload.length);
						}

						@Override
						public void onClose(int code, String reason) {
							System.out.println("onClose reason=" + reason);
						}

						@Override
						public void onOpen() {
							System.out.println("onOpen");
							showtext("連線成功");
							// wsc.sendTextMessage("Hello!");
							// wsc.disconnect();
						}
						@Override
						public void onRawTextMessage(byte[] payload) {
							System.out.println("onRawTextMessage size="
									+ payload.length);
						}

						@Override
						public void onTextMessage(String payload) {
							System.out.println("onTextMessage" + payload);
							showtext(payload);
						}

					});
		} catch (WebSocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		switch (id) {
			case R.id.bt :
				wsc.sendTextMessage("我是客戶端,我通過ws往伺服器發資料");
				break;
			case R.id.bt1 :
				connect();
				break;
			default :
				break;
		}
	}
	private void showtext(String msg) {
		Toast.makeText(this, msg, 0).show();
	}
}
下面是伺服器程式碼:

用的是jetty7自帶的websocket庫

package com.websocket;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocket.OnTextMessage;
import org.eclipse.jetty.websocket.WebSocketServlet;

public class ChatWebSocketServlet extends WebSocketServlet {

	private static final long serialVersionUID = 911879078000755859L;

	private List<MyWebSocket> list = new ArrayList<MyWebSocket>();

	class MyWebSocket implements OnTextMessage {
		private String userName = "匿名使用者";

		public MyWebSocket(String userName) {
			if (userName != null && userName.length() > 0) {
				this.userName = userName;
			}
		}

		private Connection conn;

		public void onClose(int arg0, String arg1) {
			// TODO Auto-generated method stub
			System.out.println("onOpen 斷開連線了。。。。。。。。" + arg1 + "  " + arg0);
			list.remove(this);
		}

		public void onOpen(Connection arg0) {
			// TODO Auto-generated method stub
			System.out
					.println("onOpen 連線了。。。。。。。。。。。。" + arg0.getMaxIdleTime());
			this.conn = arg0;
			
			if (!list.contains(arg0)) {
				list.add(this);
			} else {
				System.out.println("這個使用者已經連線了");
			}
			System.out.println(".." + list.size());
		}

		public void onMessage(String arg0) {
			
			String toname = arg0.substring(0, 3);
			System.out.println("toname-->" + toname);
			try {
				
				list.get(0).getConn()
						.sendMessage(arg0.substring(3));
				System.out.println("傳送的資料" + arg0.substring(3));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		private Connection getConn() {
			return this.conn;
		}
	}

	public WebSocket doWebSocketConnect(HttpServletRequest arg0, String arg1) {
		// TODO Auto-generated method stub
		String name = "";
		name = arg0.getParameter("username");
		System.out.println(name + "is connected");
		return new MyWebSocket(name);
	}

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.service(request, response);
	}

}

歡迎交流,轉載請註明出處。