在上一篇中给出的例程只能完成一次通信,完成一次通信后服务器端和客户端都将断开链接,这一篇提供多次通信的例程。
Android客户端和Python服务器通信(一):
https://www.jianshu.com/p/a9981b943013
Python服务器端:
from socket import *
import easygui
test="test01"
# 1 定义域名和端口号
HOST,PORT ='',555
# 2 定义缓冲区(缓存)
BUFFER_SIZE = 1024
ADDR=(HOST,PORT)
# 3 创建服务器套接字 AF_INET:IPv4 SOCK_STREAM:协议
tcpServerSocket = socket(AF_INET,SOCK_STREAM)
# 4 绑定域名和端口号
tcpServerSocket.bind(ADDR)
# 5 监听连接 最大连接数
tcpServerSocket.listen(5)
# 6 定义一个循环 目的:等待客户端的连接
while True:
# 6.1 打开一个客户端对象 同意连接
tcpClientSocket,addr = tcpServerSocket.accept()
print(addr)
# 连接成功后就弹出界面
while True:
Yes_or_No = easygui.buttonbox("socket01是否发送数据?", choices = ['Yes','No','退出'])
if Yes_or_No=='退出':break
if Yes_or_No=='Yes':
tcpClientSocket.send(test.encode())
Android客户端:
package com.example.mrzheng.socket02;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import java.io.InputStream;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private final int HANDLER_MSG_TELL_RECV = 0x124;
@SuppressLint("HandlerLeak")
Handler handler01 = new Handler(){
public void handleMessage(Message msg){
//接受到服务器信息时执行
Toast.makeText(MainActivity.this,(msg.obj).toString(),Toast.LENGTH_LONG).show();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startNetThread();
}
private void startNetThread() {
new Thread() {
@Override
public void run() {
try {
Socket socket = new Socket("192.168.2.200", 555);
InputStream is = socket.getInputStream();
byte[] bytes = new byte[1024];
int n =is.read(bytes);
while(true) {
Message msg = handler01.obtainMessage(HANDLER_MSG_TELL_RECV, new String(bytes, 0, n));
msg.sendToTarget();
n =is.read(bytes);
}
} catch (Exception e) {
}
}
}.start();
}
}
网友评论