重点参考长链接http://blog.csdn.net/fengyuzhengfan/article/details/38830115

http://blog.csdn.net/Jsagacity/article/details/78531819#

http://www.runoob.com/w3cnote/android-tutorial-socket1.html

1 电脑(或ESP8266)连接WIFI,建立服务 192.168.3.8  8080

1.1 查看电脑地址

1.2 电脑建立服务 192.168.3.8  8080

2 手机连接WIFI,创建客户申请服务

手机在wifi 下分配的地址是 192.168.3.9

2.1 手机打开软件

点击发送

电脑接收

2手机端工程

手机端分为两个工程

1短链接。发送完消息就自动断开。不牵扯链接中断问题,但无法接收消息。

2长连接。发送完消息还可以接收消息。实现数据互传,但是还没有加入重链接功能。

2.1 AsyncTask建立的短链接

1 布局管理

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. tools:context="com.example.dongdong.myapplication.MainActivity">
  8.  
  9. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  10. xmlns:tools="http://schemas.android.com/tools"
  11. android:id="@+id/LinearLayout1"
  12. android:layout_width="fill_parent"
  13. android:layout_height="fill_parent"
  14. android:orientation="vertical"
  15. tools:context=".MainActivity"
  16. android:weightSum="1">
  17.  
  18. <LinearLayout
  19. android:layout_width="fill_parent"
  20. android:layout_height="wrap_content"
  21. android:orientation="horizontal"
  22. android:gravity="center"
  23. android:weightSum="1">
  24.  
  25. <TextView
  26. android:layout_width="wrap_content"
  27. android:layout_height="wrap_content"
  28. android:text="IP:"
  29. android:layout_weight="0.04" />
  30. <EditText
  31. android:id="@+id/SIP"
  32. android:layout_width="wrap_content"
  33. android:layout_height="wrap_content"
  34. android:layout_weight="0.65" />
  35. <TextView
  36. android:layout_width="wrap_content"
  37. android:layout_height="wrap_content"
  38. android:text="端口:"/>
  39. <EditText
  40. android:id="@+id/IPort"
  41. android:layout_width="wrap_content"
  42. android:layout_height="wrap_content"
  43. android:layout_weight="0.17" />
  44.  
  45. </LinearLayout>
  46.  
  47. <LinearLayout
  48. android:layout_width="fill_parent"
  49. android:layout_height="wrap_content"
  50. android:orientation="horizontal"
  51. android:gravity="left"
  52. android:weightSum="1">
  53. <Button
  54. android:layout_width="wrap_content"
  55. android:layout_height="wrap_content"
  56. android:text="连接"/>
  57.  
  58. <Button
  59. android:id="@+id/bt_send"
  60. android:layout_width="88dp"
  61. android:layout_height="wrap_content"
  62. android:text="发送"
  63. android:layout_below="@+id/tv_content"
  64. android:layout_alignParentStart="true"
  65. tools:layout_editor_absoluteY="0dp"
  66. tools:layout_editor_absoluteX="8dp" />
  67.  
  68. <Button
  69. android:layout_width="wrap_content"
  70. android:layout_height="wrap_content"
  71. android:text="清空"/>
  72. </LinearLayout>
  73.  
  74. <LinearLayout
  75. android:layout_width="fill_parent"
  76. android:layout_height="wrap_content"
  77. android:orientation="vertical"
  78. android:gravity="left"
  79. android:weightSum="1">
  80. <TextView
  81. android:layout_width="wrap_content"
  82. android:layout_height="wrap_content"
  83. android:text="发送区:"
  84. android:layout_weight="0.04" />
  85.  
  86. <EditText
  87. android:id="@+id/sentText"
  88. android:layout_width="fill_parent"
  89. android:layout_height="wrap_content" />
  90.  
  91. <TextView
  92. android:id="@+id/tv_send_text"
  93. android:layout_width="241dp"
  94. android:layout_height="43dp"
  95.  
  96. android:text="发送的内容"
  97. android:layout_below="@+id/bt_send"
  98. tools:layout_editor_absoluteX="8dp"
  99. tools:layout_editor_absoluteY="8dp"
  100.  
  101. android:layout_weight="0.03" />
  102. </LinearLayout>
  103. <LinearLayout
  104. android:layout_width="fill_parent"
  105. android:layout_height="wrap_content"
  106. android:orientation="vertical"
  107. android:gravity="left"
  108. android:weightSum="1"
  109. android:layout_weight="0.12">
  110. <TextView
  111. android:layout_width="wrap_content"
  112. android:layout_height="wrap_content"
  113. android:text="接收区:"
  114. />
  115. <Button
  116. android:layout_width="wrap_content"
  117. android:layout_height="wrap_content"
  118. android:text="清空"/>
  119. <TextView
  120. android:id="@+id/tv_content"
  121. android:layout_width="wrap_content"
  122. android:layout_height="wrap_content"
  123.  
  124. android:gravity="left"
  125. android:text="接收的内容"
  126. android:layout_alignParentTop="true"
  127. android:layout_alignParentStart="true"
  128. tools:layout_editor_absoluteY="0dp"
  129. tools:layout_editor_absoluteX="8dp" />
  130. </LinearLayout>
  131. </LinearLayout>
  132.  
  133. </android.support.constraint.ConstraintLayout>

  

  

  2 添加网络权限

  1. <uses-permission android:name="android.permission.INTERNET"/>  

  

  3 工程目录

1采用AsyncTask 异步模式

输入参数问题

2.1  函数输入参数1可以设置输入参数,可以是控件

SendAsyncTask myTask = new SendAsyncTask(SIP_target,IPort__target);

2.2 

   myTask.execute(str);

对应这个参数是

doInBackground(String... params)

  

  1. package com.example.dongdong.myapplication;
  2.  
  3. import android.support.v7.app.AppCompatActivity;
  4. import android.os.Bundle;
  5. import android.os.Handler;
  6. import android.os.Message;
  7.  
  8. import android.view.View;
  9. import android.view.View.OnClickListener;
  10.  
  11. import android.widget.TextView;
  12. import android.widget.EditText;
  13. import android.widget.Button;
  14. import android.widget.Toast;
  15.  
  16. public class MainActivity extends AppCompatActivity implements OnClickListener {
  17.  
  18. // 1.1 定义
  19. private Button bt_send;
  20. private TextView tv_content;
  21. private TextView tv_send_text;
  22.  
  23. private EditText SIP;
  24. private EditText IPort;
  25. private EditText sentText;
  26.  
  27. @Override
  28. protected void onCreate(Bundle savedInstanceState) {
  29. super.onCreate(savedInstanceState);
  30. setContentView(R.layout.activity_main);
  31. // 1.2 控件初始化
  32. InitView();
  33. // 2 开启服务器
  34. MobileServer mobileServer = new MobileServer();
  35. mobileServer.setHandler(handler);
  36. new Thread(mobileServer).start();
  37.  
  38. }
  39.  
  40. private void InitView() {
  41. tv_content = (TextView) findViewById(R.id.tv_content);
  42. tv_send_text = (TextView) findViewById(R.id.tv_send_text);
  43.  
  44. sentText=(EditText) findViewById(R.id.sentText);
  45. SIP=(EditText) findViewById(R.id.SIP);
  46. IPort=(EditText) findViewById(R.id.IPort);
  47.  
  48. bt_send = (Button) findViewById(R.id.bt_send);
  49. bt_send.setOnClickListener(this);
  50.  
  51. }
  52.  
  53. @Override
  54. public void onClick(View v) {
  55. switch (v.getId()) {
  56. case R.id.bt_send:
  57. // String str = "Sent to the ESP8266";
  58. String str="请输入命令";
  59. int IPort__target=8080;
  60. String SIP_target="192.168.1.1";
  61. if( sentText!=null)
  62. {
  63. str=sentText.getText().toString().trim();
  64. }
  65. if (SIP!= null) {
  66. SIP_target=SIP.getText().toString().trim();
  67.  
  68. }
  69. if (IPort!= null) {
  70. String msg = IPort.getText().toString().trim();
  71. if (msg != null && msg.length() > 0) {
  72. IPort__target = Integer.parseInt(msg);
  73. }
  74. }
  75. // 链接IP
  76. SendAsyncTask myTask = new SendAsyncTask(SIP_target,IPort__target);
  77. //SendAsyncTask myTask = new SendAsyncTask();
  78. // 初始发送的消息
  79. myTask.execute(str);
  80.  
  81. tv_send_text.setText(str);
  82. break;
  83. }
  84.  
  85. }
  86.  
  87. Handler handler = new Handler() {
  88. @Override
  89. public void handleMessage(Message msg) {
  90. switch (msg.what) {
  91. case 1:
  92. tv_content.setText("WiFi模块发送的:" + msg.obj);
  93. Toast.makeText(MainActivity.this, "接收到信息", Toast.LENGTH_LONG)
  94. .show();
  95. }
  96. }
  97. };
  98. }

  

  

  

  1. package com.example.dongdong.myapplication;
  2.  
  3. import java.io.IOException;
  4.  
  5. import java.net.ServerSocket;
  6. import java.net.Socket;
  7.  
  8. import java.io.DataInputStream;
  9.  
  10. import android.os.Handler;
  11. import android.os.Message;
  12.  
  13. public class MobileServer implements Runnable {
  14. private ServerSocket server;
  15. private DataInputStream in;
  16. private byte[] receice;
  17.  
  18. private Handler handler = new Handler();
  19.  
  20. public MobileServer() {
  21. }
  22.  
  23. public void setHandler(Handler handler) {
  24. this.handler = handler;
  25. }
  26.  
  27. @Override
  28. public void run() {
  29.  
  30. try {
  31. //5000是手机端开启的服务器的端口号,ESP8266进行TCP连接时使用的端口,而IP也是通过指令查询的联入设备的IP
  32. server = new ServerSocket(5000);
  33. while (true) {
  34. Socket client = server.accept();
  35. in = new DataInputStream(client.getInputStream());
  36. receice = new byte[50];
  37. in.read(receice);
  38. in.close();
  39.  
  40. Message message = new Message();
  41. message.what = 1;
  42. message.obj = new String(receice);
  43. handler.sendMessage(message);
  44. }
  45.  
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. }
  49. try {
  50. server.close();
  51. } catch (IOException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55. }

  

  1. package com.example.dongdong.myapplication;
  2.  
  3. import java.io.IOException;
  4. import java.io.PrintStream;
  5. import java.net.Socket;
  6. import android.os.AsyncTask;
  7.  
  8. public class SendAsyncTask extends AsyncTask<String, Void, Void> {
  9. // public class SendAsyncTask extends AsyncTask<String, Void, Void> {
  10.  
  11. //这里是连接ESP8266的IP和端口号,IP是通过指令在单片机开发板查询到,而端口号可以自行设置,也可以使用默认的,333就是默认的
  12. private static String IP ;
  13. private static int PORT ;
  14.  
  15. private Socket client = null;
  16. private PrintStream out = null;
  17.  
  18. public SendAsyncTask(String ip,int port)
  19. {
  20. super();
  21. this.IP = ip;
  22. this.PORT = port; }
  23.  
  24. @Override
  25. protected Void doInBackground(String... params) {
  26. String str = params[0];
  27. try {
  28. client = new Socket(IP, PORT);
  29. client.setSoTimeout(5000);
  30. // 获取Socket的输出流,用来发送数据到服务端
  31. out = new PrintStream(client.getOutputStream());
  32. out.print(str);
  33. out.flush();
  34.  
  35. if (client == null) {
  36. return null;
  37. } else {
  38. out.close();
  39. client.close();
  40. }
  41.  
  42. } catch (IOException e) {
  43. e.printStackTrace();
  44. }
  45.  
  46. return null;
  47. }
  48.  
  49. }

2 Handler 建立的长连接

功能描述

  1. 建立长链接,链接按钮建立链接 ,发射按钮发射信号,停止按钮结束。也可以改成短链接,生成类的时候把信号加进去。
  2. 界面和通信线程各自有访问彼此的Handler,从而实现数据线程互传互传。
  3. 主界面之外,建立通信线程发送消息。通信线程里又新建一个线程,用于专门接收服务器的数据。

现有问题

  1. 若连超时异常处理
  2. 若连接上但之后中断,连接重检测问题。

工程代码

如果自己新建工程要加入这些代码,注意修改工程名字。一般每个文件的第一行,只一句根据实际建立的工程确定。

2.1 网路权限

  1. <uses-permission android:name="android.permission.INTERNET"/>  

 添加后完成整的代码

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.espressif.myapplication">
  4. <uses-permission android:name="android.permission.INTERNET"/>  
  5. <application
  6. android:allowBackup="true"
  7. android:icon="@mipmap/ic_launcher"
  8. android:label="@string/app_name"
  9. android:roundIcon="@mipmap/ic_launcher_round"
  10. android:supportsRtl="true"
  11. android:theme="@style/AppTheme">
  12. <activity android:name=".MainActivity">
  13. <intent-filter>
  14. <action android:name="android.intent.action.MAIN" />
  15.  
  16. <category android:name="android.intent.category.LAUNCHER" />
  17. </intent-filter>
  18. </activity>
  19. </application>
  20.  
  21. </manifest>

  

 

2 布局文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. >
  8.  
  9. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  10. xmlns:tools="http://schemas.android.com/tools"
  11. android:id="@+id/LinearLayout1"
  12. android:layout_width="fill_parent"
  13. android:layout_height="fill_parent"
  14. android:orientation="vertical"
  15. tools:context=".MainActivity"
  16. android:weightSum="1">
  17.  
  18. <LinearLayout
  19. android:layout_width="fill_parent"
  20. android:layout_height="wrap_content"
  21. android:orientation="horizontal"
  22. android:gravity="center"
  23. android:weightSum="1">
  24.  
  25. <TextView
  26. android:layout_width="wrap_content"
  27. android:layout_height="wrap_content"
  28. android:text="IP:"
  29. android:layout_weight="0.04" />
  30. <EditText
  31. android:id="@+id/SIP"
  32. android:layout_width="wrap_content"
  33. android:layout_height="wrap_content"
  34. android:layout_weight="0.65"
  35. android:text="192.168.1.102"
  36. />
  37. <TextView
  38. android:layout_width="wrap_content"
  39. android:layout_height="wrap_content"
  40. android:text="端口:"/>
  41. <EditText
  42. android:id="@+id/IPort"
  43. android:layout_width="wrap_content"
  44. android:layout_height="wrap_content"
  45. android:layout_weight="0.17"
  46. android:text="8080"
  47. />
  48.  
  49. </LinearLayout>
  50.  
  51. <LinearLayout
  52. android:layout_width="fill_parent"
  53. android:layout_height="wrap_content"
  54. android:orientation="horizontal"
  55. android:gravity="left"
  56. android:weightSum="1">
  57. <Button
  58. android:id="@+id/bt_connect"
  59. android:layout_width="wrap_content"
  60. android:layout_height="wrap_content"
  61. android:text="连接"/>
  62.  
  63. <Button
  64. android:id="@+id/bt_send"
  65. android:layout_width="88dp"
  66. android:layout_height="wrap_content"
  67. android:text="发送"
  68. android:layout_below="@+id/tv_content"
  69. android:layout_alignParentStart="true"
  70. tools:layout_editor_absoluteY="0dp"
  71. tools:layout_editor_absoluteX="8dp" />
  72.  
  73. <Button
  74. android:id="@+id/bt_stop"
  75. android:layout_width="wrap_content"
  76. android:layout_height="wrap_content"
  77. android:text=""/>
  78. </LinearLayout>
  79.  
  80. <LinearLayout
  81. android:layout_width="fill_parent"
  82. android:layout_height="wrap_content"
  83. android:orientation="vertical"
  84. android:gravity="left"
  85. android:weightSum="1">
  86. <TextView
  87. android:layout_width="wrap_content"
  88. android:layout_height="wrap_content"
  89. android:text="发送区:"
  90. android:layout_weight="0.04" />
  91.  
  92. <EditText
  93. android:id="@+id/sentText"
  94. android:layout_width="fill_parent"
  95. android:layout_height="wrap_content" />
  96.  
  97. <TextView
  98. android:id="@+id/tv_send_text"
  99. android:layout_width="241dp"
  100. android:layout_height="43dp"
  101.  
  102. android:text="发送的内容"
  103. android:layout_below="@+id/bt_send"
  104. tools:layout_editor_absoluteX="8dp"
  105. tools:layout_editor_absoluteY="8dp"
  106.  
  107. android:layout_weight="0.03" />
  108. </LinearLayout>
  109. <LinearLayout
  110. android:layout_width="fill_parent"
  111. android:layout_height="wrap_content"
  112. android:orientation="vertical"
  113. android:gravity="left"
  114. android:weightSum="1"
  115. android:layout_weight="0.12">
  116. <TextView
  117. android:layout_width="wrap_content"
  118. android:layout_height="wrap_content"
  119. android:text="接收区:"
  120. />
  121. <Button
  122. android:layout_width="wrap_content"
  123. android:layout_height="wrap_content"
  124. android:text="清空"/>
  125. <TextView
  126. android:id="@+id/tv_content"
  127. android:layout_width="wrap_content"
  128. android:layout_height="wrap_content"
  129.  
  130. android:gravity="left"
  131. android:text="接收的内容"
  132. android:layout_alignParentTop="true"
  133. android:layout_alignParentStart="true"
  134. tools:layout_editor_absoluteY="0dp"
  135. tools:layout_editor_absoluteX="8dp" />
  136. </LinearLayout>
  137. </LinearLayout>
  138.  
  139. </android.support.constraint.ConstraintLayout>

 

3 工程文件 

  1. package com.espressif.myapplication;
  2.  
  3. import android.support.v7.app.AppCompatActivity;
  4. import android.os.Bundle;
  5. import android.os.Handler;
  6. import android.os.Message;
  7.  
  8. import android.view.View;
  9. import android.view.View.OnClickListener;
  10.  
  11. import android.widget.TextView;
  12. import android.widget.EditText;
  13. import android.widget.Button;
  14. import android.widget.Toast;
  15.  
  16. public class MainActivity extends AppCompatActivity implements OnClickListener {
  17. // 1.1 定义
  18. private Button bt_connect;// 链接
  19. private Button send;// 发送
  20. private Button bt_stop; //停止
  21.  
  22. public TextView tv_content; // 显示接收的命令
  23. private TextView tv_send_text; // 显示发送的命令
  24.  
  25. private EditText SIP; //IP地址
  26. private EditText IPort; //端口
  27. private EditText sentText; // 发送内容
  28. // 1.2 定义与服务器通信的子线程
  29. boolean isConnect=true;//连接还是断开
  30. ClientThread clientThread;
  31. Handler handler;
  32.  
  33. // 2 主函数
  34. @Override
  35. protected void onCreate(Bundle savedInstanceState) {
  36. super.onCreate(savedInstanceState);
  37. setContentView(R.layout.activity_main);
  38.  
  39. // 2.1 控件初始化
  40. InitView();
  41.  
  42. }
  43.  
  44. // 1 界面控件初始化
  45. private void InitView() {
  46. tv_content = (TextView) findViewById(R.id.tv_content);
  47. tv_send_text = (TextView) findViewById(R.id.tv_send_text);
  48.  
  49. sentText=(EditText) findViewById(R.id.sentText);
  50. SIP=(EditText) findViewById(R.id.SIP);
  51. IPort=(EditText) findViewById(R.id.IPort);
  52.  
  53. send = (Button) findViewById(R.id.bt_send);
  54. send.setOnClickListener(this);
  55.  
  56. bt_connect=(Button) findViewById(R.id.bt_connect);
  57. bt_connect.setOnClickListener(this);
  58. bt_stop = (Button) findViewById(R.id.bt_stop);
  59. bt_stop.setOnClickListener(this);
  60.  
  61. // 2.2 用于和主界面通信
  62. handler = new Handler() {
  63. @Override
  64. public void handleMessage(Message msg) {
  65. switch (msg.what) {
  66. case 0x123:
  67. tv_content.setText("WiFi模块发送的:" + msg.obj.toString());
  68. // tv_content.append("\n" + msg.obj.toString());
  69. break;
  70. }
  71. }
  72. };
  73.  
  74. }
  75. // 2 链接TCP/IP 链接目标服务
  76. public void connectIP(){
  77.  
  78. int IPort__target=8080;
  79. String SIP_target="192.168.1.1";
  80.  
  81. if (SIP!= null) {
  82. SIP_target=SIP.getText().toString().trim();
  83.  
  84. }
  85. if (IPort!= null) {
  86. String msg = IPort.getText().toString().trim();
  87. if (msg != null && msg.length() > 0) {
  88. IPort__target = Integer.parseInt(msg);
  89. }
  90. }
  91.  
  92. // 2 开启服务器
  93. if (isConnect == true) //标志位 = true表示连接
  94. {
  95.  
  96. // 链接IP
  97.  
  98. clientThread = new ClientThread(handler);
  99. clientThread.setip_port(SIP_target, IPort__target);
  100. new Thread(clientThread).start();
  101.  
  102. if(clientThread.isConnect==false){
  103. // if(clientThread.s.isConnected()&& !clientThread.s.isClosed()){
  104. isConnect = true;//置为true
  105. bt_connect.setText("连接");//按钮上显示连接
  106.  
  107. }
  108. else{
  109. isConnect = false;//置为false
  110. bt_connect.setText("断开");//按钮上显示--断开
  111. }
  112. }
  113. else //标志位 = false表示退出连接
  114. {
  115. isConnect = true;//置为true
  116. bt_connect.setText("连接");//按钮上显示连接
  117. clientThread.stop_connect();
  118. }
  119. }
  120. // 3 发送信息
  121. public void Sendmsg(){
  122.  
  123. String msg="1123";
  124. if( sentText!=null)
  125. {
  126. msg=sentText.getText().toString();
  127. }
  128. //更新文本框
  129. tv_send_text.setText(msg);
  130. // 发送函数
  131. try {
  132. Message msga = new Message();
  133. msga.what = 0x345;
  134. msga.obj = sentText.getText().toString();
  135. clientThread.revHandler.sendMessage(msga);
  136.  
  137. }
  138. catch (Exception e)
  139. {
  140. e.printStackTrace();
  141. tv_send_text.setText("发送失败!");
  142. }
  143.  
  144. }
  145.  
  146. // 4 按键点击触发器
  147. @Override
  148. public void onClick(View v) {
  149. switch (v.getId()) {
  150.  
  151. //1链接函数
  152. case R.id.bt_connect:
  153. connectIP();
  154. break;
  155.  
  156. //2 发送信息
  157. case R.id.bt_send:
  158. Sendmsg();
  159. break;
  160. // 停止
  161. case R.id.bt_stop:
  162. // 停止函数
  163. break;
  164. }
  165. }
  166.  
  167. }

  

  1. package com.espressif.myapplication;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.DataInputStream;
  5. import java.io.OutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStreamReader;
  8. import java.net.Socket;
  9. import android.os.Handler;
  10. import android.os.Looper;
  11. import android.os.Message;
  12. import android.text.TextUtils;
  13.  
  14. import java.net.SocketTimeoutException;
  15.  
  16. public class ClientThread implements Runnable
  17. {
  18. private static int Port_target;
  19. private static String IP_target;
  20. boolean isConnect=true;//连接还是断开
  21. public Socket s;
  22. // 该线程所处理的Socket所对应的输入流
  23. BufferedReader br =null;
  24. // 输出
  25. OutputStream os =null;
  26.  
  27. // 定义向UI线程发送消息的Handler对象
  28. private Handler handler;
  29. // 定义接收UI线程的消息的Handler对象
  30. public Handler revHandler;
  31.  
  32. // 2.1设置通线程向主界面通信对象
  33. public ClientThread(Handler handler) {
  34. this.handler = handler; // 定义向UI线程发送消息的Handler对象
  35. }
  36.  
  37. // 2.2设置链接地址
  38. public void setip_port(String IP,int port){
  39. IP_target=IP;
  40. Port_target=port;
  41. }
  42. // 2.3从服务器接收信息线程
  43. public void connectthread(){
  44. // 启动一条子线程来读取服务器响应的数据
  45. new Thread()
  46. { String content =null;
  47. @Override
  48. public void run()
  49. {
  50. // 不断读取Socket输入流中的内容。
  51. try
  52. {
  53. while ((content = br.readLine())!=null)
  54. {
  55. // 每当读到来自服务器的数据之后,发送消息通知程序界面显示该数据
  56. Message msg =new Message();
  57. msg.what = 0x123;
  58. msg.obj = content;
  59. handler.sendMessage(msg);
  60. }
  61. }
  62. catch (IOException e)
  63. {
  64. e.printStackTrace();
  65. }
  66. }
  67. }.start();
  68.  
  69. }
  70. // 2.4将接收命令更新主界面显示框
  71. public void fruh_UI(){
  72.  
  73. // 为当前线程初始化Looper
  74. Looper.prepare();
  75. // 创建revHandler对象
  76. revHandler =new Handler()
  77. {
  78. @Override
  79. public void handleMessage(Message msg)
  80. {
  81. // 接收到UI线程中用户输入的数据
  82. if (msg.what == 0x345)
  83. {
  84. // 将用户在文本框内输入的内容写入网络
  85. try
  86. {
  87. os.write((msg.obj.toString() + "\r\n")
  88. .getBytes("utf-8"));
  89. }
  90. catch (Exception e)
  91. {
  92. e.printStackTrace();
  93. }
  94. }
  95. }
  96. };
  97. // 启动Looper
  98. Looper.loop();
  99. }
  100.  
  101. // 2.4终止链接
  102. public void stop_connect(){
  103. try
  104. {
  105.  
  106. isConnect = false;
  107. s.close();//关闭连接
  108. s = null;
  109.  
  110. }
  111. catch (IOException e)
  112. {
  113. e.printStackTrace();
  114. }
  115. }
  116.  
  117. public void run()
  118. {byte[] acceptdata1=null;
  119. try
  120. {
  121. s =new Socket(IP_target, Port_target);
  122. if(s.isConnected()&& !s.isClosed()){isConnect=true;}
  123. // 接收数据
  124. br =new BufferedReader(new InputStreamReader( s.getInputStream()));
  125. //存放数据
  126. os =s.getOutputStream();
  127.  
  128. // 新线程 接收数据
  129. connectthread();
  130. // 更新主界面显示框
  131. fruh_UI();
  132.  
  133. }
  134. catch (SocketTimeoutException e1)
  135. { isConnect=false;
  136. System.out.println("网络连接超时!!");
  137. }
  138. catch (Exception e)
  139. {
  140. e.printStackTrace();
  141. }
  142. }
  143. }

  

1 TCP/IP通信的更多相关文章

  1. 使用Boost asio实现同步的TCP/IP通信

    可以先了解一下Boost asio基本概念,以下是Boost asio实现的同步TCP/IP通信: 服务器程序部分,如果想保留套接字之后继续通信,可以动态申请socket_type,保存指针,因为so ...

  2. 使用Boost asio实现异步的TCP/IP通信

    可以先了解一下Boost asio基本概念,以下是Boost asio实现的异步TCP/IP通信: 服务器: #include "stdafx.h" #include <io ...

  3. TCP/IP 通信

    TCP/IP 通信又叫socket 通信,是基于TCP/IP协调面向连接的一个数据传输技术.是属于OSI国际标准的传输层,三次握手 提供数据,有序,安全,端到端的传输和接收.它有三个主要协议:传输控制 ...

  4. tcp/ip通信第5期之服务器端程序

    /* 此程序是tcp/ip通信服务器端程序,测试运行在redhat5上 重构readline函数,解决粘包问题——利用“\n”识别一个消息边界 */ #include<stdio.h> # ...

  5. tcp/ip通信第5期之客户机端程序

    /*此程序是tcp/ip通信的客户机端程序, 测试运行在redhat6系统上 重构readline函数,解决粘包问题——利用“\n”识别一个消息边界 */ #include<stdio.h> ...

  6. 第4章 TCP/IP通信案例:访问Internet上的Web服务器

    第4章 TCP/IP通信案例:访问Internet上的Web服务器 4.2 部署代理服务器 书中为了演示访问Internet上的Web服务器的全过程,使用了squid代理服务器程序模拟了一个代理服务器 ...

  7. TCP/IP通信过程(以发送电子邮件为例)(转)

    1.应用程序处理 (1)A用户启动邮件应用程序,填写收件人邮箱和发送内容,点击“发送”,开始TCP/IP通信: (2)应用程序对发送的内容进行编码处理,这一过程相当于OSI的表示层功能: (3)由A用 ...

  8. linux高性能服务器编程 (四) --TCP/IP通信案例

    第四章 TCP/IP通信案例 HTTP代理服务器的大致工作原理        在HTTP通信链上,客户端和服务器之间通常存在某些中转代理服务器.它们提供对目标资源的中转访问.一个HTTP请求可能被多个 ...

  9. TCP/IP通信网络基础

    TCP/IP是互联网相关的各类协议族的总称. TCP/IP的分层管理 分层的优点:如果只有一个协议在互联网上统筹,某个地方修改就要把所有的部分整体换掉,采用分层则只需要改变相应的层.把各个接口部分规划 ...

  10. tcp/ip通信传输流

    利用TCP/IP协议族进行网络通信时,会通过分层顺序与对方进行通信,发送端从应用层往下走,接收端则往应用层方向走. 我们用HTTP进行举例 客户端在应用层发出想要看到某个web页面的http请求.HT ...

随机推荐

  1. effective VBA

    For Append As: Open "1.txt" For Append As #1Open "1.txt"就是打开名为1.txt的文件For Append ...

  2. 一个很好用的SqlHelper类

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  3. 理解JVM之垃圾收集器概述

    前言 很多人将垃圾收集(Garbage Collection)视为Java的伴生产物,实际1960年诞生的Lisp是第一门真正使用内存动态分配与垃圾手机技术的语言.在目前看来,内存的动态分配与内存回收 ...

  4. MySQL设计之三范式的理解

    转自:https://blog.csdn.net/wangqyoho/article/details/52900585 设计关系数据库时,遵从不同的规范要求,设计出合理的关系型数据库,这些不同的规范要 ...

  5. 排序算法(10)--Distribution Sorting--分布排序[2]--Radix Sort--基数排序

    1.基本思想 基数排序是通过“分配”和“收集”过程来实现排序 2.实现原理 基数排序(以整形为例),将整形10进制按每位拆分,然后从低位到高位依次比较各个位.主要分为两个过程: (1)分配,先从个位开 ...

  6. css语法和基本知识

    1.CSS全称为“层叠样式表”,它主要是用于定义HTML内容在浏览器内的显示样式,如文字大小.颜色.字体加粗等. 注:使用CSS样式的一个好处是通过定义某个样式,可以让不同网页位置的文字有着统一的字体 ...

  7. BZOJ3108 [cqoi2013]图的逆变换

    Description 定义一个图的变换:对于一个有向图\(G=(V, E)\),建立一个新的有向图: \(V'=\{v_e|e \in E\}\),\(E'=\{(v_b, v_e)|b=(u,v) ...

  8. node 搭建静态服务

    对于Node.js新手,搭建一个静态资源服务器是个不错的锻炼,从最简单的返回文件或错误开始,渐进增强,还可以逐步加深对http的理解. 基本功能 不急着写下第一行代码,而是先梳理一下就基本功能而言有哪 ...

  9. 【代码笔记】iOS-获得现在的时间(2015-09-11)

    一,代码. - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, ...

  10. Flutter Dart中的异步

    以下内容从官网得到: https://webdev.dartlang.org/articles/performance/event-loop Even-Looper Dart是单线程模型,也就没有了所 ...