Android客户端套接字未连接到python服务器套接字

时间:2020-08-28 15:18:49

标签: java python android sockets networking

所以我用python创建了这台服务器,并用python客户端和java客户端(两者都与服务器cuz在同一台PC上运行,但我只有一台PC)进行了测试,以确保它们都可以正常工作。但是,当我从android创建套接字(在同一wifi而不是模拟器上)并尝试将其连接到服务器时,出现以下异常https://i.stack.imgur.com/WrT9P.png。 以下是python服务器代码

import socket
import tkinter as tk
from threading import Thread
import pyqrcode
from PIL import ImageTk, Image
import time
import re
from tkinter import messagebox


def close_window():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        gui.stop_connection()
        window.destroy()

class GUI:
    def __init__(self, root):
        self.listen_socket = None
        self.data = ''
        self.running = 0
        self.addr = None
        self.conn = None
        self.thread = None

        self.label = tk.Label(root, text="Your qr code will be displayed below",
                              bg='#05499E', fg='white', padx=10, pady=10)
        self.label.pack(padx=10, pady=10)

        self.host_name = socket.gethostname()
        ip_add = socket.gethostbyname(self.host_name)
        qr = pyqrcode.create(ip_add, mode='binary')
        save = qr.png('ip_add.png', 9)
        self.my_img = ImageTk.PhotoImage(Image.open('I:\\Pycharm Projects\\QRCodeApp\\ip_add.png'))
        self.image_label = tk.Label(image=self.my_img)
        self.image_label.pack(padx=10, pady=10)

        self.start_btn = tk.Button(
            window, text="Start connection",
            command=self.start_connection, fg='#05499E', bg='white',
            font=('Helvetica', 16), bd=2, padx=5, pady=5, relief='solid'
        )
        self.start_btn.pack(padx=10, pady=10)

        self.stop_btn = tk.Button(
            window, text="Stop connection",
            command=self.stop_connection, fg='#05499E', bg='white',
            font=('Helvetica', 16), bd=2, padx=5, pady=5, relief='solid'
        )
        self.stop_btn.pack(pady=10)

        self.connection_status = tk.Label(
            root, text="Not connected", fg='red', font=('Helvetica', 16)
        )
        self.connection_status.pack(pady=10)

    def socket_thread(self):
        print("Thread started...")
        self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        port = 65432
        host = '192.168.56.1'
        self.listen_socket.bind((host, port))
        print(f"Server is listening on port {port}")
        self.listen_socket.listen(10)
        while self.running != 0:
            if self.conn is None:
                try:
                    print('Before accepting')
                    (self.conn, self.addr) = self.listen_socket.accept()
                    print(f"Client is at address {self.addr[0]}, on port {self.addr[1]}")
                    self.connection_status.configure(text='Connected!', fg='green')

                except socket.timeout as se:
                    print("Connection timeout")

                except Exception as e:
                    print('Exception while connecting : ' + str(e))

            if self.conn is not None:
                print(f"Connected to {self.conn}, at {self.addr}")
                self.data = ''
                while self.data != 'done':
                    self.data = ''
                    try:
                        self.data = str(self.conn.recv(1024).decode('utf-8'))
                        match = re.search('[A-Za-z0-9].*[A-Za-z0-9]', self.data)
                        self.data = match.group()

                    except Exception as e:
                        print("Socket error : " + str(e))

                    if len(self.data):
                        print('Got data :', self.data)
                    elif self.running == 0:
                        print('Tired of waiting for connection')
                        self.data = 'done'
                        # self.stop_connection()
                print('Closing connection...')
                self.conn = None
                self.connection_status.configure(text="Not connected", fg='red')
                print('Connection closed.')

        print("Closing listener...")
        self.conn.close()
        self.listen_socket.close()

    def start_connection(self):
        if self.running == 0:
            print('Starting thread...')
            self.running = 1
            self.thread = Thread(target=self.socket_thread)
            self.thread.start()
        else:
            print('Thread already running !')

    def stop_connection(self):

        if self.running:
            print('Stopping thread...')
            self.connection_status.configure(text="Not connected", fg='red')
            self.running = 0
            self.thread.join(timeout=0.05)
            self.thread = None
            self.data = ''
            print('thread stopped')
        else:
            print('Thread not running!')


window = tk.Tk()
window.title("QR Code Generator")
window.iconbitmap("qr.ico")
window.configure(bg='#0E7EFF')
window.geometry('400x600+500+50')
window.pack_slaves()

gui = GUI(window)

window.protocol("WM_DELETE_WINDOW", close_window)
window.mainloop()

和我实际建立连接的android消息发送活动代码

package com.example.qrandbarcode;

import android.os.AsyncTask;
import android.util.Log;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class MessageSender extends AsyncTask<String, Void, Void> {
    DataOutputStream dos;
    Socket socket;

    @Override
    protected Void doInBackground(String... voids) {
        String message = voids[0];
        Log.e("REACHED MESSENGER CLASS", "outside try catch");
        try{
            Log.e("BEFORE SOCKET CREATION", "Socket will be created after this");
            socket = new Socket("192.168.56.1", 65432);
            Log.e("CONNECTION", "status: " + socket.isConnected());
            dos = new DataOutputStream(socket.getOutputStream());
            dos.writeUTF(message);
            dos.flush();
            dos.close();
        }catch (IOException e) {
            Log.e("EXCEPTION OCCURRED", "couldn't connect" + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}
以下是异常的堆栈跟踪
E/REACHED MESSENGER CLASS: outside try catch
E/BEFORE SOCKET CREATION: Socket will be created after this
E/EXCEPTION OCCURRED: couldn't connectfailed to connect to /192.168.56.1 (port 65432) from /:: (port 57684): connect failed: ETIMEDOUT (Connection timed out)
W/System.err: java.net.ConnectException: failed to connect to /192.168.56.1 (port 65432) from /:: (port 57684): connect failed: ETIMEDOUT (Connection timed out)
请注意,Python GUI上的所有功能均正常运行。请告诉我那里有什么问题?我知道套接字无法连接到服务器的一件事。

0 个答案:

没有答案