首页

基于TCP socket,Android客户端与PC通信,客户端源码

java

2020-8-2


基于TCP~socket,Android客户端与PC通信,客户端源码。已经测试,可用。附带apk,和网络调试助手,方便测试。只需提供服务器的IP和端口号,即可通信。

客户端:一次连接,可发送多次数据。

重点是客户端时时接收服务器端发送来的数据。采用 Handler和Thead结合。

项目中包含了 网络调试助手V3.8.1.exe  demoClientTcpIp.apk以及项目源码

package com.example.democlienttcpip;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.Charset;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.Toast;

public class MainActivity<Params> extends TabActivity implements
		OnClickListener {

	private EditText edtIP;
	private EditText edtPort;
	EditText edtSend;
	private EditText edtReceiver;

	private Button btnConn;
	private Button btnSend;

	private CheckBox checkBoxTimer;

	private String tag = "MainActivity";

	InputStream in;
	PrintWriter printWriter = null;
	BufferedReader reader;

	Socket mSocket = null;
	public boolean isConnected = false;

	private MyHandler myHandler;

	Thread receiverThread;

	CheckBoxListener listener;

	private class MyReceiverRunnable implements Runnable {

		public void run() {

			while (true) {

				Log.i(tag, "---->>client receive....");
				if (isConnected) {
					if (mSocket != null && mSocket.isConnected()) {

						String result = readFromInputStream(in);

						try {

							// String str = "";
							//
							// while ((str = reader.readLine()) != null) {
							// Log.i(tag, "---->> read data:"   str);
							// result  = str;
							// }
							if (!result.equals("")) {

								Message msg = new Message();
								msg.what = 1;
								Bundle data = new Bundle();
								data.putString("msg", result);
								msg.setData(data);
								myHandler.sendMessage(msg);
							}

						} catch (Exception e) {
							Log.e(tag, "--->>read failure!"   e.toString());
						}
					}
				}
				try {
					Thread.sleep(100L);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}
	}

	private class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			receiverData(msg.what);
			if (msg.what == 1) {
				String result = msg.getData().get("msg").toString();
				edtReceiver.append(result);
			}
		}
	}

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


	private void init() {

		edtIP = (EditText) this.findViewById(R.id.id_edt_inputIP);
		edtPort = (EditText) this.findViewById(R.id.id_edt_inputport);
		edtSend = (EditText) this.findViewById(R.id.id_edt_sendArea);
		edtReceiver = (EditText) findViewById(R.id.id_edt_jieshou);

		checkBoxTimer = (CheckBox) this.findViewById(R.id.id_checkBox_timer);
		listener = new CheckBoxListener(this);
		checkBoxTimer.setOnCheckedChangeListener(listener);

		btnSend = (Button) findViewById(R.id.id_btn_send);
		btnSend.setOnClickListener(this);
		btnConn = (Button) findViewById(R.id.id_btn_connClose);
		btnConn.setOnClickListener(this);

		myHandler = new MyHandler();
	}

	/******************************************************************************/
	public String readFromInputStream(InputStream in) {
		int count = 0;
		byte[] inDatas = null;
		try {
			while (count == 0) {
				count = in.available();
			}
			inDatas = new byte[count];
			in.read(inDatas);
			return new String(inDatas, "gb2312");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/******************************************************************************/

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		// 启动2个工作线程:发送、接收。
		case R.id.id_btn_connClose:

			connectThread();
			break;

		case R.id.id_btn_send:

			sendData();
			break;
		}
	}

	/**
	 * 当连接到服务器时,可以触发接收事件.
	 */
	private void receiverData(int flag) {

		if (flag == 2) {
			// mTask = new ReceiverTask();
			receiverThread = new Thread(new MyReceiverRunnable());
			receiverThread.start();

			Log.i(tag, "--->>socket 连接成功!");
			btnConn.setText("断开");

			isConnected = true;
			// mTask.execute(null);
		}

	}

	/**
	 * 发送数据线程.
	 */
	private void sendData() {

		// sendThread.start();
		try {
			String context = edtSend.getText().toString();

			if (printWriter == null || context == null) {

				if (printWriter == null) {
					showInfo("连接失败!");
					return;
				}
				if (context == null) {
					showInfo("连接失败!");
					return;
				}
			}

			printWriter.print(context);
			printWriter.flush();
			Log.i(tag, "--->> client send data!");
		} catch (Exception e) {
			Log.e(tag, "--->> send failure!"   e.toString());

		}
	}

	/**
	 * 启动连接线程.
	 */
	private void connectThread() {
		if (!isConnected) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					Looper.prepare();
					Log.i(tag, "---->> connect/close server!");

					connectServer(edtIP.getText().toString(), edtPort.getText()
							.toString());
				}
			}).start();
		} else {
			try {
				if (mSocket != null) {
					mSocket.close();
					mSocket = null;
					Log.i(tag, "--->>取消server.");
					// receiverThread.interrupt();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			btnConn.setText("连接");
			isConnected = false;
		}
	}

	// 连接服务器.(网络调试助手的服务器端编码方式:gb2312)
	private void connectServer(String ip, String port) {
		try {
			Log.e(tag, "--->>start connect  server !"   ip   ","   port);

			mSocket = new Socket(ip, Integer.parseInt(port));
			Log.e(tag, "--->>end connect  server!");

			OutputStream outputStream = mSocket.getOutputStream();

			printWriter = new PrintWriter(new BufferedWriter(
					new OutputStreamWriter(outputStream,
							Charset.forName("gb2312"))));
			listener.setOutStream(printWriter);
			// reader = new BufferedReader(new InputStreamReader(
			// mSocket.getInputStream()));

			in = mSocket.getInputStream();
			myHandler.sendEmptyMessage(2);

			showInfo("连接成功!");
		} catch (Exception e) {
			isConnected = false;
			showInfo("连接失败!");
			Log.e(tag, "exception:"   e.toString());
		}

	}

	private void showInfo(String msg) {
		Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();

	}
}
资源下载此资源下载价格为3D币(VIP免费),请先
资源文件列表
TCP-IP/demoClientTcpIp/.classpath , 475
TCP-IP/demoClientTcpIp/.project , 851
TCP-IP/demoClientTcpIp/.settings/org.eclipse.jdt.core.prefs , 177
TCP-IP/demoClientTcpIp/AndroidManifest.xml , 1952
TCP-IP/demoClientTcpIp/bin/AndroidManifest.xml , 1952
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/BuildConfig.class , 363
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/CheckBoxListener$MyTask.class , 1141
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/CheckBoxListener.class , 3522
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/MainActivity$1.class , 1346
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/MainActivity$MyHandler.class , 1475
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/MainActivity$MyReceiverRunnable.class , 2606
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/MainActivity.class , 7783
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/R$attr.class , 367
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/R$dimen.class , 488
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/R$drawable.class , 434
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/R$id.class , 808
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/R$layout.class , 430
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/R$menu.class , 415
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/R$string.class , 499
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/R$style.class , 458
TCP-IP/demoClientTcpIp/bin/classes/com/example/democlienttcpip/R.class , 763
TCP-IP/demoClientTcpIp/bin/classes.dex , 1080628
TCP-IP/demoClientTcpIp/bin/demoClientTcpIp.apk , 325201
TCP-IP/demoClientTcpIp/bin/dexedLibs/android-support-v4-15f25747000aa01e079e900c517a8de7.jar , 273766
TCP-IP/demoClientTcpIp/bin/dexedLibs/annotations-469187a931caf2600a63e55eaf3aa79d.jar , 910
TCP-IP/demoClientTcpIp/bin/jarlist.cache , 120
TCP-IP/demoClientTcpIp/bin/res/crunch/drawable-hdpi/ic_launcher.png , 5964
TCP-IP/demoClientTcpIp/bin/res/crunch/drawable-mdpi/ic_launcher.png , 3112
TCP-IP/demoClientTcpIp/bin/res/crunch/drawable-xhdpi/ic_launcher.png , 9355
TCP-IP/demoClientTcpIp/bin/res/crunch/drawable-xxhdpi/ic_launcher.png , 17889
TCP-IP/demoClientTcpIp/bin/resources.ap_ , 42401
TCP-IP/demoClientTcpIp/gen/com/example/democlienttcpip/BuildConfig.java , 169
TCP-IP/demoClientTcpIp/gen/com/example/democlienttcpip/R.java , 2778
TCP-IP/demoClientTcpIp/ic_launcher-web.png , 51394
TCP-IP/demoClientTcpIp/libs/android-support-v4.jar , 758727
TCP-IP/demoClientTcpIp/lint.xml , 53
TCP-IP/demoClientTcpIp/proguard-project.txt , 781
TCP-IP/demoClientTcpIp/project.properties , 563
TCP-IP/demoClientTcpIp/res/drawable-hdpi/ic_launcher.png , 7658
TCP-IP/demoClientTcpIp/res/drawable-mdpi/ic_launcher.png , 3777
TCP-IP/demoClientTcpIp/res/drawable-xhdpi/ic_launcher.png , 12516
TCP-IP/demoClientTcpIp/res/drawable-xxhdpi/ic_launcher.png , 24777
TCP-IP/demoClientTcpIp/res/layout/activity_main.xml , 7275
TCP-IP/demoClientTcpIp/res/menu/main.xml , 339
TCP-IP/demoClientTcpIp/res/values/dimens.xml , 220
TCP-IP/demoClientTcpIp/res/values/strings.xml , 227
TCP-IP/demoClientTcpIp/res/values/styles.xml , 697
TCP-IP/demoClientTcpIp/res/values-w820dp/dimens.xml , 381
TCP-IP/demoClientTcpIp/src/com/example/democlienttcpip/CheckBoxListener.java , 2418
TCP-IP/demoClientTcpIp/src/com/example/democlienttcpip/MainActivity.java , 6830
TCP-IP/demoClientTcpIp.apk , 325350
TCP-IP/═°┬τ╡≈╩╘╓·╩╓V3.8.1.exe , 1025024
没有账号? 忘记密码?

社交账号快速登录