android与python服务器socket通信

时间:2022-10-22 17:59:23
pythonserver.py
#创建TCP服务器 from socket import *
#返回时间的 from time import ctime
#定义域名和端口号 HOST,PORT='',8088 #创建缓冲区的大小(1M) BUFFER_SIZE=1024 ADDR=("localhost",PORT)
#创建服务器的套接字 第一个参数代表IP 第二个基于TCP的数据流 代表TCP/IP协议的编程 tcpServerSocket = socket(AF_INET,SOCK_STREAM)
#绑定域名和端口号 tcpServerSocket.bind(ADDR)
#监听连接,传入连接请求的最大数 tcpServerSocket.listen(6)
print('服务器创建成功,等待客户的连接。。。')
#等待客户的连接 while True:
    #客户端的连接对象  tcpClientSocket,addr = tcpServerSocket.accept()
    print('连接服务器的客户端对象:',addr)
    #定义一个循环开始接受数据  while True:
        #请求是连接到客户端TCP套接字,接受缓冲区读取字节的长度 decode()解码 bytes --> str  data = tcpClientSocket.recv(BUFFER_SIZE).decode()
        if not data:
            break  print('data=',data)
        #发送的时间信息  tcpClientSocket.send(('[%s] %s'%(ctime(),data)).encode())
    # 关闭资源  tcpClientSocket.close()
tcpServerSocket.close()

 
activity_main.xml
 
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"  tools:context="com.example.asus.clienttextdemo.MainActivity">

    <EditText  android:id="@+id/client_host_ip"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:hint="请输入ip地址"/>

    <EditText  android:id="@+id/client_port_ip"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:hint="请输入端口号"/>

    <EditText  android:id="@+id/client_content_ip"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:hint="请输入要发给服务器的内容"/>

   <Button  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:id="@+id/client_submit"  android:text="提交数据"/>

</LinearLayout>

MainActivity.java
 
 
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.JsonHttpRequestCallback;
import cn.finalteam.okhttpfinal.RequestParams;

public class MainActivity extends AppCompatActivity {

    private final int HANDLER_MSG_TELL_RECV = 0x124;
    private EditText client_host_ip, client_port, client_content;
    private Button client_submit;

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            //设置一个弹框  AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setMessage("python服务器的数据显示:" + msg.obj);
            //创建弹框 并展示  builder.create().show();
        }
    };


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

        private void initEvent() {
        client_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String host = client_host_ip.getText().toString();
                String port = client_port.getText().toString();
                String content = client_content.getText().toString();

                Toast.makeText(MainActivity.this,host+","+port+","+content,Toast.LENGTH_LONG).show();
                //启动网络线程处理数据  startNetThread(host,Integer.parseInt(port),content);
            }
        });
    }

    private void startNetThread(final String host, final int port, final String data) {
        new Thread() {
            public void run() {
                try {
                    //创建客户端对象  Socket socket = new Socket(host, port);
                    //获取客户端对象的输出流  OutputStream outputStream = socket.getOutputStream();
                    //把内容以字节流的形式写入(data).getBytes();  outputStream.write(data.getBytes());
                    //刷新流管道  outputStream.flush();
                    System.out.println("打印客户端中的内容:" + socket);
                    //拿到客户端输入流  InputStream is = socket.getInputStream();

                    byte[] bytes = new byte[1024];
                    //回应数据  int n = is.read(bytes);
                    System.out.println(new String(bytes, 0, n));
                    Message msg = handler.obtainMessage(HANDLER_MSG_TELL_RECV, new String(bytes, 0, n));
                    msg.sendToTarget();
                    //关闭流  is.close();
                    //关闭客户端  socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //启动线程  }.start();
    }



    //初始化控件  private void initViews() {
        client_host_ip = findViewById(R.id.client_host_ip);
        client_port = findViewById(R.id.client_port_ip);
        client_content = findViewById(R.id.client_content_ip);
        client_submit = findViewById(R.id.client_submit);
    }
}