andriod studio tcp client通讯的实现
【andriod studio tcp client通讯的实现】主要参考了以下链接
http://blog.csdn.net/shankezh/article/details/70763579
对于重连的出错处理好像有点问题。
1 我的布局
2 tcpclient代码
package com.example.lenovo.chentcpclient; import android.content.Intent; import android.util.Log; import java.io.BufferedReader; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import com.example.lenovo.chentcpclient.MainActivity; /** * Created by Lenovo on 2018/2/22. */ public class TcpClient implements Runnable{ private String TAG = "TcpClient"; private StringserverIP = "192.168.88.141"; private int serverPort = 1234; private PrintWriter pw; private InputStream is; private DataInputStream dis; private boolean isRun = true; private Socket socket = null; byte buff[]= new byte[4096]; private String rcvMsg; private int rcvLen; public TcpClient(String ip , int port){ this.serverIP = ip; this.serverPort = port; }public void closeSelf(){ isRun = false; }public void send(String msg){ pw.println(msg); pw.flush(); }@Override public void run() { try { socket = new Socket(serverIP,serverPort); socket.setSoTimeout(5000); pw = new PrintWriter(socket.getOutputStream(),true); is = socket.getInputStream(); dis = new DataInputStream(is); } catch (IOException e) { e.printStackTrace(); } while (isRun){ try { rcvLen = dis.read(buff); rcvMsg = new String(buff,0,rcvLen,"utf-8"); Log.i(TAG, "run: 收到消息:"+ rcvMsg); Intent intent =new Intent(); intent.setAction("tcpClientReceiver"); intent.putExtra("tcpClientReceiver",rcvMsg); MainActivity.context.sendBroadcast(intent); //将消息发送给主界面 if (rcvMsg.equals("QuitClient")){//服务器要求客户端结束 isRun = false; } } catch (IOException e) { e.printStackTrace(); }} try { pw.close(); is.close(); dis.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } }}
3 mainactivity的代码
package com.example.lenovo.chentcpclient; import android.annotation.SuppressLint; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.lang.ref.WeakReference; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Handler; import com.example.lenovo.chentcpclient.TcpClient; public class MainActivity extends AppCompatActivity { private String TAG = "FuncTcpClient"; @SuppressLint("StaticFieldLeak") public static Context context ; private Button btconnect = null; private Button btclose= null; private Button btclearreceivetext = null; private Button btclearsendtext = null; private Button btsend = null; private TextView textip = null; private TextView textport = null; private TextView textreceive = null; private TextView textsend = null; private TextView textsendnow = null; private static TcpClient tcpClient = null; private final MyHandler myHandler = new MyHandler(this); private MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver(); ExecutorService exec = Executors.newCachedThreadPool(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = this; btconnect = (Button) findViewById(R.id.button_connect); btclose = (Button) findViewById(R.id.button_close); btclearreceivetext = (Button) findViewById(R.id.button_clrecv); btclearsendtext = (Button) findViewById(R.id.button_clsend); btsend = (Button) findViewById(R.id.button_send); textip = (TextView) findViewById(R.id.editText_ip); textport = (TextView) findViewById(R.id.editText_port); textreceive = (TextView) findViewById(R.id.editText_receive); textsend = (TextView) findViewById(R.id.editText_send); textsendnow = (TextView) findViewById(R.id.editText_sendnow); btconnect.setOnClickListener(listener); btclose.setOnClickListener(listener); btclearreceivetext.setOnClickListener(listener); btclearsendtext.setOnClickListener(listener); btsend.setOnClickListener(listener); bindReceiver(); Ini(); } private View.OnClickListener listener = new View.OnClickListener() { public void onClick(View v) { if (v == btconnect) { Log.i(TAG, "onClick: 开始"); btconnect.setEnabled(false); btclose.setEnabled(true); btsend.setEnabled(true); tcpClient = new TcpClient(textip.getText().toString(),getPort(textport.getText().toString())); exec.execute(tcpClient); } if (v == btclose) { tcpClient.closeSelf(); btconnect.setEnabled(true); btclose.setEnabled(false); btsend.setEnabled(false); } if (v == btclearreceivetext) { textreceive.setText(""); } if (v == btclearsendtext) { textsend.setText(""); } if (v == btsend) { Message message = Message.obtain(); message.what = 2; message.obj = textsendnow.getText().toString(); myHandler.sendMessage(message); exec.execute(new Runnable() { @Override public void run() { tcpClient.send(textsendnow.getText().toString()); } }); } } }; private class MyHandler extends android.os.Handler{ private WeakReferencemActivity; MyHandler(MainActivity activity){ mActivity = new WeakReference (activity); }@Override public void handleMessage(Message msg) { if (mActivity != null){ switch (msg.what){ case 1: textreceive.append(msg.obj.toString()); break; case 2: textsend.append(msg.obj.toString()); break; } } } }private class MyBroadcastReceiver extends BroadcastReceiver{@Override public void onReceive(Context context, Intent intent) { String mAction = intent.getAction(); switch (mAction){ case "tcpClientReceiver": String msg = intent.getStringExtra("tcpClientReceiver"); Message message = Message.obtain(); message.what = 1; message.obj = msg; myHandler.sendMessage(message); break; } } }private int getPort(String msg){ if (msg.equals("")){ msg = "1234"; } return Integer.parseInt(msg); }private void bindReceiver(){ IntentFilter intentFilter = new IntentFilter("tcpClientReceiver"); registerReceiver(myBroadcastReceiver,intentFilter); } private void Ini(){ btclose.setEnabled(false); btsend.setEnabled(false); } }
推荐阅读
- CVE-2020-16898|CVE-2020-16898 TCP/IP远程代码执行漏洞
- android|android studio中ndk的使用
- Android|Android JNI之静态注册(android studio)
- 计算机网络基础TCP\HTTP\HTTPS
- TCP长连接与段链接
- TCP组件设计篇(详细设计)
- Android|Android Studio 的 Browse Repositories 下载不了插件
- 工具|Wireshark抓包对其字TCP段理解
- 网络|网络编程释疑(TCP连接拔掉网线后会发生什么)
- 服务器未能释放tcp连接,TCP连接的建立和释放