android實現socket連接(客戶端)

學習socket通信,做了一個Demo,兩臺手機之間建立socket通信,今天先放出client端,歡迎大家交流。


public class MainActivity extends Activity {
	EditText mIP;// 輸入的IP
	EditText mContent;// 發送內容
	Button mBtn;// 發送按鈕
	Button mLogin;// 連接按鈕
	TextView mData;
	private String ip = null;// IP地址
	private int port = 8001;// 端口號
	private Socket socket;
	OutputStream output = null;// 輸出流
	DataInputStream inputStream;
	String context = null;
	Handler mHandler;
	Handler handler;

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

		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case 0x100:
					Toast.makeText(MainActivity.this, "已連接", Toast.LENGTH_SHORT).show();
					break;
				case 0x300:
					Bundle bundle = msg.getData();
					// 將十六進制字節顯示爲十六進制字符串
					// mData.append(Bytes2HexString(bundle.getByteArray("byte"))+"\n");
					//將字節數組顯示爲字符串
					 mData.append((bundle.getByteArray("byte"))+"\n");
					// 將字符串顯示出來
					//mData.append(bundle.getString("byte") + "\n");
					break;
				default:
					break;
				}
			}
		};
	}

	private void init() {
		mLogin.setOnClickListener(new BtnOnclick());
		mBtn.setOnClickListener(new BtnOnclick());

	}

	class BtnOnclick implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.X_Login:
				ip = mIP.getText().toString();// 獲取輸入的IP地址
				if (ip != null) {
					new Thread(new LoginThread()).start();// 新線程建立連接
					new Thread(new DoThread()).start();// 新線程發送
				} else {
					Toast.makeText(getApplicationContext(), "請輸入IP地址", Toast.LENGTH_SHORT).show();
				}
				break;
			case R.id.X_SendBtn:
				if (ip != null) {
					mData.append(mContent.getText().toString()+"\n");
					Bundle bundle = new Bundle();
					Message message = Message.obtain();
					// 獲取發送的內容,傳到子線程的輸出流發送
					bundle.putString("context", mContent.getText().toString());
					message.setData(bundle);
					handler.sendMessage(message);
				} else {
					Toast.makeText(getApplicationContext(), "請輸入IP地址", Toast.LENGTH_SHORT).show();
				}
				break;
			default:
				break;
			}
		}

	}

	private void findview() {
		mIP = (EditText) findViewById(R.id.X_IP_Edit);
		mContent = (EditText) findViewById(R.id.X_Content_Edit);
		mBtn = (Button) findViewById(R.id.X_SendBtn);
		mLogin = (Button) findViewById(R.id.X_Login);
		mData = (TextView) findViewById(R.id.X_data);
	}

	public class LoginThread implements Runnable {
		@Override
		public void run() {
			try {
				// 建立一個socket連接
				socket = new Socket(ip, 8001);
				// 獲取輸入流
				inputStream = new DataInputStream(socket.getInputStream());
				output = socket.getOutputStream();// 獲取輸出流
				mHandler.sendEmptyMessage(0x100);// 提示已連接
				while (true) {
					try {// 此線程循環讀取
						byte[] buff = {};
						Message msg1 = Message.obtain();
						buff = new byte[inputStream.available()];
						if (buff.length != 0) {// 如果不是十六位 的字節數組 打印出來
							inputStream.read(buff);// 讀取到緩存中
							Bundle bundle = new Bundle();
							// 1.傳遞字節數組 與UT8-8編碼相同通信,
							 bundle.putByteArray("byte", buff);
							// 2.傳遞字符串 與PC端通信需要把GBK轉爲UTF-8
							//bundle.putString("byte", new String(buff, "gbk"));
							msg1.setData(bundle);
							msg1.what = 0x300;
							mHandler.sendMessage(msg1);
						}
					} catch (IOException e) {
						// 如果有異常發出此提示
						mHandler.sendEmptyMessage(0x600);
					}
				}
			} catch (IOException e) {
				mHandler.sendEmptyMessage(0x200);
			}
		}
	}

	public class DoThread implements Runnable {
		@Override
		public void run() {
			Looper.prepare();
			handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					super.handleMessage(msg);
					Bundle bundle = msg.getData();
					try {
						//發送UTF-8編碼
						output.write(bundle.getString("context").getBytes("UTF-8"));
						//發送GBK編碼
						//output.write(bundle.getString("context").getBytes("GBK"));
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
			Looper.loop();
		}
	}

	private void CloseSocket() {
		try {
			inputStream.close();
			output.close();// 關閉輸出流
			socket.close();// 關閉 socket
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private final static byte[] hex = "0123456789ABCDEF".getBytes();

	public static String Bytes2HexString(byte[] b) {
		byte[] buff = new byte[2 * b.length];
		for (int i = 0; i < b.length; i++) {
			buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
			buff[2 * i + 1] = hex[b[i] & 0x0f];
		}
		return new String(buff);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		CloseSocket();
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章