http://www.cnblogs.com/yangfengwu/p/8776712.html
先把源码和资料链接放到这里
链接:https://pan.baidu.com/s/10MxI8-Q33-M_R2WEHqEi1A 密码:j1sz
先做手机的,然后做C#的
详细点的可以看我这篇文章,请参考着这篇看这篇文章,这篇文章会解决一些细节问题
http://www.cnblogs.com/yangfengwu/p/5212570.html
咱们不做很复杂的直接越简单越好,就做成这样
先编译一下
不用管,后期的话咱会用一下
最后做成这样子
发现还是有点大..
把像素低的放到像素高的里面图片显示出来会缩小,把像素高的放到像素低的里面图片显示出来会放大
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageViewLamp = (ImageView) findViewById(R.id.imageView1); switchLamp = (Switch) findViewById(R.id.switch1); switchLamp.setOnCheckedChangeListener(switchLamplistener);//设置SWITCH的状态改变事件 } private OnCheckedChangeListener switchLamplistener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub // Toast.makeText(getApplicationContext(), isChecked+"", 500).show(); if (isChecked) {//切换图片 imageViewLamp.setImageResource(R.drawable.ledon); } else { imageViewLamp.setImageResource(R.drawable.ledoff); } } };
现在做点击连接按钮就连接服务器
刚看到...............
有点迫不及待的想试一试腾讯云了,
下面做的是:点击连接按钮,连接TCP服务器,连接上以后启动数据接收任务,因为数据接收任务可以判断是不是和服务器断开了连接
然后按钮显示"断开",如果意外断开了连接也显示断开....
public class MainActivity extends Activity { ImageView imageViewLamp;//灯的图片 Switch switchLamp;//灯的控制开关 EditText editTextIPAdress,editTextPort;//ip地址和端口号的编辑框 Button buttonConnect;//连接按钮 Socket socket;//cocket boolean ConnectFlage = false;//连接标志,控制按钮显示连接和断开 ThreadConnectService threadConnectService = new ThreadConnectService();//建立一个连接任务的变量 InputStream inputStream;//获取输入流,可以用来判断有没有断开连接 ThreadReadData threadReadData = new ThreadReadData();//接收数据的任务的变量 boolean threadReadDataFlage = false;//接收数据任务一直运行控制 byte[] ReadBuffer = new byte[1024];//存储接收到的数据 int ReadBufferLengh = 0;//接收到的数据个数 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextIPAdress = (EditText) findViewById(R.id.editText1); editTextPort = (EditText) findViewById(R.id.editText2); buttonConnect = (Button) findViewById(R.id.button1); buttonConnect.setOnClickListener(buttonConnectClick); imageViewLamp = (ImageView) findViewById(R.id.imageView1); switchLamp = (Switch) findViewById(R.id.switch1); switchLamp.setOnCheckedChangeListener(switchLamplistener); } /*指示灯控制开关*/ private OnCheckedChangeListener switchLamplistener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { imageViewLamp.setImageResource(R.drawable.ledon); } else { imageViewLamp.setImageResource(R.drawable.ledoff); } } }; /*按钮点击连接事件*/ private OnClickListener buttonConnectClick = new OnClickListener() { @Override public void onClick(View v) { if (ConnectFlage) { try { threadConnectService.start();//启动连接任务 } catch (Exception e) //预防任务还没关闭呢又点击开始 { threadConnectService.run(); } } else { ConnectFlage = true; buttonConnect.setText("连接"); try { socket.close();//关闭socket inputStream.close();//关闭数据流 } catch (Exception e) { // TODO: handle exception } } } }; /** * 连接服务器的任务 * @author yang * */ class ThreadConnectService extends Thread { public void run() { InetAddress ipAddress; try { ipAddress = InetAddress.getByName(editTextIPAdress.getText().toString());//获取IP地址 int port =Integer.valueOf(editTextPort.getText().toString());//获取端口号 socket = new Socket(ipAddress, port);//创建连接地址和端口 inputStream = socket.getInputStream();//获得通道的数据流变量 threadReadDataFlage = true;//一直接收数据 try { threadReadData.start(); } catch (Exception e) {//预防任务还没关闭呢又点击开始 threadReadData.run(); } runOnUiThread(new Runnable() {//修改界面的UI最好用Handle,这里力求简单,下几节再用 public void run() { ConnectFlage = false; buttonConnect.setText("断开"); Toast.makeText(getApplicationContext(), "连接成功", 500).show(); } }); } catch (Exception e) { e.printStackTrace(); } } } /** * 接收数据的任务 * @author yang * */ class ThreadReadData extends Thread { public void run() { while (threadReadDataFlage) { try { ReadBufferLengh = inputStream.read(ReadBuffer);//服务器断开会返回-1 if (ReadBufferLengh == -1) { threadReadDataFlage = false; runOnUiThread(new Runnable() {//修改界面的UI最好用Handle,这里力求简单,下几节再用 public void run() { ConnectFlage = true; buttonConnect.setText("连接"); Toast.makeText(getApplicationContext(), "与服务器断开连接", 500).show(); } }); } } catch (Exception e) { // TODO Auto-generated catch block Log.e("error", ReadBufferLengh+""); e.printStackTrace(); } } } } /** 当活动(界面)不再可见时调用 */ @Override protected void onStop() { threadReadDataFlage = false;//结束接收数据任务 super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
忘了说一件事情....加权限
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.yfw456.tcpclientdemo" android:versionCode="1" android:versionName="1.0" > <!-- 获取手机信息权限 --> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>" <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission> <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.WAKE_LOCK"/> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.WRITE_SETTINGS" /> <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"> </uses-permission> <uses-permission android:name="android.permission.RECEIVE_SMS"/> <uses-sdk android:minSdkVersion="17" android:targetSdkVersion="21" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
我把上面做的打包了
好现在接着写发数据(控制灯的亮灭)
public class MainActivity extends Activity { ImageView imageViewLamp;//灯的图片 Switch switchLamp;//灯的控制开关 EditText editTextIPAdress,editTextPort;//ip地址和端口号的编辑框 Button buttonConnect;//连接按钮 Socket socket;//cocket boolean ConnectFlage = true;//连接标志,控制按钮显示连接和断开 ThreadConnectService threadConnectService = new ThreadConnectService();//建立一个连接任务的变量 InputStream inputStream;//获取输入流,可以用来判断有没有断开连接 OutputStream outputStream;//获得输出流 ThreadReadData threadReadData = new ThreadReadData();//接收数据的任务 ThreadSendData threadSendData = new ThreadSendData();//发送数据的任务 boolean threadReadDataFlage = false;//接收数据任务一直运行控制 boolean threadSendDataFlage = false;//接收数据任务一直运行控制 byte[] ReadBuffer = new byte[1024];//存储接收到的数据 byte[] SendBuffer = new byte[1024];//存储发送的数据 int ReadBufferLengh = 0; int SendDataCnt = 0;//控制发送数据的个数 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextIPAdress = (EditText) findViewById(R.id.editText1); editTextPort = (EditText) findViewById(R.id.editText2); buttonConnect = (Button) findViewById(R.id.button1); buttonConnect.setOnClickListener(buttonConnectClick); imageViewLamp = (ImageView) findViewById(R.id.imageView1); switchLamp = (Switch) findViewById(R.id.switch1); switchLamp.setOnCheckedChangeListener(switchLamplistener); } /*指示灯控制开关*/ private OnCheckedChangeListener switchLamplistener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { imageViewLamp.setImageResource(R.drawable.ledon); SendBuffer[0] = (byte) 0xaa; SendBuffer[1] = 0x55; SendBuffer[2] = 0x02; SendBuffer[3] = (byte) 0xff; } else { imageViewLamp.setImageResource(R.drawable.ledoff); SendBuffer[0] = (byte) 0xaa; SendBuffer[1] = 0x55; SendBuffer[2] = 0x02; SendBuffer[3] = 0x00; } SendDataCnt = 4;//控制发送数据的个数 } }; /*按钮点击连接事件*/ private OnClickListener buttonConnectClick = new OnClickListener() { @Override public void onClick(View v) { if (ConnectFlage) { try { threadConnectService.start();//启动连接任务 } catch (Exception e) //预防任务还没关闭呢又点击开始 { threadConnectService.run(); } } else { ConnectFlage = true; threadSendDataFlage = false;//关掉发送任务,预防产生多的任务 threadReadDataFlage = false;//关掉接收任务,预防产生多的任务 buttonConnect.setText("连接"); try { socket.close();//关闭socket inputStream.close();//关闭数据流 } catch (Exception e) { // TODO: handle exception } } } }; /** * 连接服务器的任务 * @author yang * */ class ThreadConnectService extends Thread { public void run() { InetAddress ipAddress; try { ipAddress = InetAddress.getByName(editTextIPAdress.getText().toString());//获取IP地址 int port =Integer.valueOf(editTextPort.getText().toString());//获取端口号 socket = new Socket(ipAddress, port);//创建连接地址和端口 inputStream = socket.getInputStream();//获得通道的数据流 outputStream = socket.getOutputStream();//获得通道的输出流 threadReadDataFlage = true;//一直接收数据 threadSendDataFlage = true;//一直循环的判断是否发送数据 try { threadReadData.start(); } catch (Exception e) {//预防任务还没关闭呢又点击开始 threadReadData.run(); } try { threadSendData.start(); } catch (Exception e) { threadSendData.run(); } runOnUiThread(new Runnable() {//修改界面的UI最好用Handle,这里力求简单,下几节再用 public void run() { ConnectFlage = false; buttonConnect.setText("断开"); Toast.makeText(getApplicationContext(), "连接成功", 500).show(); } }); } catch (Exception e) { e.printStackTrace(); } } } /** * 接收数据的任务 * @author yang * */ class ThreadReadData extends Thread { public void run() { while (threadReadDataFlage) { try { ReadBufferLengh = inputStream.read(ReadBuffer);//服务器断开会返回-1 if (ReadBufferLengh == -1) { threadSendDataFlage = false;//关掉发送任务,预防产生多的任务 threadReadDataFlage = false;//关掉接收任务,预防产生多的任务 SendDataCnt = 0;//清零发送的个数 ConnectFlage = true; runOnUiThread(new Runnable() {//修改界面的UI最好用Handle,这里力求简单,下几节再用 public void run() { buttonConnect.setText("连接"); Toast.makeText(getApplicationContext(), "与服务器断开连接", 500).show(); } }); } } catch (Exception e) { // TODO Auto-generated catch block Log.e("error", ReadBufferLengh+""); e.printStackTrace(); runOnUiThread(new Runnable() {//修改界面的UI最好用Handle,这里力求简单,下几节再用 public void run() { buttonConnect.setText("连接"); Toast.makeText(getApplicationContext(), "与服务器断开连接", 500).show(); } }); ConnectFlage = true; threadSendDataFlage = false;//关掉发送任务,预防产生多的任务 threadReadDataFlage = false;//关掉接收任务,预防产生多的任务 SendDataCnt = 0;//清零发送的个数 } } } } /** * 发送数据任务 * @author yang * */ class ThreadSendData extends Thread { public void run() { while (threadSendDataFlage) { if (SendDataCnt>0) //要发送的数据个数大于0 { try { outputStream.write(SendBuffer,0,SendDataCnt);//发送数据 SendDataCnt = 0;//清零发送的个数 } catch (Exception e) { runOnUiThread(new Runnable() {//修改界面的UI最好用Handle,这里力求简单,下几节再用 public void run() { buttonConnect.setText("连接"); Toast.makeText(getApplicationContext(), "与服务器断开连接", 500).show(); } }); ConnectFlage = true; threadSendDataFlage = false;//关掉发送任务,预防产生多的任务 threadReadDataFlage = false;//关掉接收任务,预防产生多的任务 SendDataCnt = 0; } } } } } /** 当活动(界面)不再可见时调用 */ @Override protected void onStop() { threadReadDataFlage = false;//结束接收数据任务 threadSendDataFlage = false;//结束发送数据任务 SendDataCnt = 0; super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
发送数据是写在了一个任务里面
整体的源码
本来想这一节也写好C#的,不过感觉写的够多的了,所以C#的放到下一节
下一篇
http://www.cnblogs.com/yangfengwu/p/8785516.html