wifi/Bluetooth的scoket编程(python 3.3>)

2024-04-26 10:26:30 发布

您现在位置:Python中文网/ 问答频道 /正文

编程新手。。关于如何用python实现这个特定的任务,我不需要什么帮助。。我需要在pc机和andriod之间传输数据。。我试过插座。。它只适用于活动的internet连接(我使用了客户机/服务器方法)。。我想用蓝牙或wifi试试,如果我用pybluez来做蓝牙。。安德烈·迪奥斯不支持。。而且它只在linux上运行,对于wifi我不知道如何开始/从哪里开始,任何建议都欢迎

我使用play store(python3.6>;)中的pythonidle3在andriod上运行python脚本,在windows上我有python3.6解释器


Tags: 方法服务器play客户机linux编程internet建议
1条回答
网友
1楼 · 发布于 2024-04-26 10:26:30

这只是寻址wifi,这是我通常使用的一般结构。在

服务器脚本:

import socket, os, time, sys, threading

HOST = '192.168.1.2' # The IP address of this server
PORT = 8888 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print('Bind failed. Error Code : ' + str(msg))
    sys.exit()

print('Socket bind complete')

#Start listening on socket
s.listen(10)
print('Socket now listening')

#Function for handling connections. This will be used to create threads
def clientthread(conn):
    try:
        #Sending message to connected client
        #print('Welcome to the server. Type something and hit enter')
        #conn.send('Welcome to the server. Type something and hit enter\n'.encode()) #send only takes string
        data = ""
        #infinite loop so that function do not terminate and thread do not end.
        toggle = True
        count = 0
        while True:
            data = ""
            #Receiving from client
            data = conn.recv(1024).decode().strip("\r")
            if data:
                print(data)
                conn.send((data + "\r").encode())
            time.sleep(.01)
    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)

    #came out of loop
    finally:
        conn.close()

#now keep talking with the client
while True:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print('Connected with ' + addr[0] + ':' + str(addr[1]))

    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
    new_thread = threading.Thread(target = clientthread , args =(conn,))
    new_thread.daemon = True
    new_thread.start()

s.close()

客户端脚本:

^{pr2}$

相关问题 更多 >