python搭建服务器实现两个Android客户端间收发消息

yipeiwu_com6年前服务器

本文为大家分享了python搭建服务器实现两个Android客户端间收发消息,供大家参考,具体内容如下

python服务器

# coding:utf-8

import socket
import threading
import time


def handle_client(client_socket, client_id):
  """处理客户端请求"""
  # 获取客户端请求数据

  while True:
    try:
      request_data = client_socket.recv(1024)
    except Exception:
      time.sleep(0.2)
      continue
    if len(request_data) > 0:
      request_lines = request_data.splitlines()
      print(request_lines[0].decode("utf-8"))
      #res = int(request_lines[0]) + 1
      client_socket_list[(client_id+1) % 2].send(bytes(str(request_lines[0].decode("utf-8"))+"\n", "utf-8"))
  client_socket_list.remove(client_id)



if __name__ == "__main__":
  server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  """
  socket()是一个函数,创建一个套接字,
  AF_INET 表示用IPV4地址族,
  SOCK_STREAM 是说是要是用流式套接字
  """
  # server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 设置地址重用
  server_socket.bind(("10.2.70.42", 8000)) # 绑定端口
  server_socket.listen(2) # 开启监听
  client_socket_list = []
  client_num = 0
  Isready = False

  while True:
    client_id = client_num
    client_socket, client_address = server_socket.accept()
    print("[%s, %s]用户连接上了" % client_address)
    handle_client_thread = threading.Thread(target=handle_client, args=(client_socket, client_id))
    """
    tartget表示这个进程到底要执行什么行为
    args是target要接受的参数
    """
    client_socket_list.append(client_socket)
    client_num += 1
    if len(client_socket_list) == 3:
      client_socket_list.pop(0)
    client_socket.setblocking(0)
    handle_client_thread.start()

Android客户端-Java代码

package com.example.administrator.wuziqi_intenet;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.URLDecoder;
import java.net.UnknownHostException;

import static com.example.administrator.wuziqi_intenet.R.id.button1;

public class MainActivity extends AppCompatActivity {

  Button button = null;
  TextView textView = null;
  EditText editText = null;
  Socket socket;
  BufferedWriter pw=null;
  BufferedReader is=null;
  String string="baba";
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    new Thread() {
      @Override
      public void run() {
          try{
            socket = new Socket("10.2.70.42", 8000);
            socket.setSoTimeout(10000);
            pw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
          } catch (IOException e) {
            e.printStackTrace();
          }

        }
      }.start();

    button = (Button) findViewById(button1);
    textView = (TextView) findViewById(R.id.textview);
    editText = (EditText) findViewById(R.id.input);

    handler.sendEmptyMessageDelayed(1, 100);

    button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        new Thread(){
          @Override
          public void run()
          {
            String msg = editText.getText().toString();
            try{
              pw.write(msg);
              pw.flush();
            } catch (UnknownHostException e) {
              Toast.makeText(MainActivity.this,"失败1",Toast.LENGTH_SHORT).show();
              e.printStackTrace();
            } catch (IOException e) {
              Toast.makeText(MainActivity.this,"失败2",Toast.LENGTH_SHORT).show();
              e.printStackTrace();
            }
          }
        }.start();
        editText.setText("");
      }
    });

  }
  private Handler handler = new Handler() {

    public void handleMessage(Message message) {
      try {
        Moving();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

  };
  private void Moving() throws IOException {
    new Thread() {
      @Override
      public void run() {
        try {
          if (is.ready())
            string = is.readLine();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }.start();
    byte[] b=string.getBytes();
    String s1=new String(b);
    System.out.println(s1);
    textView.setText(string);
    handler.sendEmptyMessageDelayed(1, 100);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用php判断服务器是否支持Gzip压缩功能

Gzip可以压缩网页大小从而达到加速打开网页的速度,目前主流的浏览器几乎都支持这个功能,但开启Gzip是需要服务器支持的,在这里我们简单的使用php来判断服务器是否支持Gzip功能。 新...

PyQt+socket实现远程操作服务器的方法示例

PyQt+socket实现远程操作服务器的方法示例

来需求了。。干活啦。。 需求内容 部分时候由于缓存刷新、验证码显示不出来或者浏览器打不开或者打开速度很慢等原因,导致部分测试同事不想使用浏览器登录服务器执行命令。 期望有小工具可以替代登...

python定时采集摄像头图像上传ftp服务器功能实现

首先是截图,从摄像头截取一幅图像: 复制代码 代码如下:while 1:   #测试摄像头的存在    try:  ...

python和shell监控linux服务器的详细代码

本文实例为大家分享了python和shell监控linux服务器的具体代码,供大家参考,具体内容如下 1、 shell监控负载 监控原理:使用uptime来获取负载的信息,然后通过字符...

Python3之简单搭建自带服务器的实例讲解

Python3之简单搭建自带服务器的实例讲解

WEB开发,我们先从搭建一个简单的服务器开始,Python自带服务模块,且python3相比于python2有很大不同, 在Python2.6版本里,/usr/bin/lib/pytho...