目录
一、TCP客户端UI
1、UI展示
2、xml代码
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#59b1ef"
tools:context=".MainActivity4">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_client_send"
android:text="发送"
android:textSize="25sp"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:onClick="btn_client_send_clicked" />
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:textSize="30sp"
android:layout_height="300dp"
android:layout_below="@id/btn_client_send"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#ffffff" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_start"
android:text="开始"
android:layout_below="@+id/text_view"
android:textSize="25sp"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:onClick="btn_start_clicked" />
<TextView
android:id="@+id/text_view2"
android:layout_width="match_parent"
android:textSize="30sp"
android:text="0"
android:layout_height="100dp"
android:layout_below="@id/btn_start"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#ffffff" />
</RelativeLayout>
二、TCP客户端数据发送
java
public void Client_SendMessage(){
try {
Socket client = new Socket("192.168.124.6",8089);
OutputStream out = client.getOutputStream();
out.write("meng".getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void btn_client_send_clicked(View v){
new Thread(new Runnable() {
@Override
public void run() {
Client_SendMessage();
}
}).start();
}
三、TCP客户端数据接收
java
textView1 = findViewById(R.id.text_view);
textView1.setText("数据接收框");
textView2 = findViewById(R.id.text_view2);
textView2.setText("0");
java
new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
Socket client = new Socket("192.168.124.6",8089);
int len;
InputStream in = client.getInputStream();
byte[] data = new byte[128];
len = in.read(data);
String str = new String(data,0,len);
Message msg2 = new Message();
Bundle b = new Bundle();
b.putString("msg", str);
msg2.setData(b);
h2.sendMessage(msg2);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}).start();
java
h2 = new Handler(){
@Override
public void handleMessage(Message msg2) {
// TODO Auto-generated method stub
super.handleMessage(msg2);
Bundle b = msg2.getData();
String string = b.getString("msg");
textView1.setText(string);
}
};