Это касается только Wi-Fi, это общая структура для того, что я обычно использую.
Серверный скрипт:
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()
Клиентский скрипт:
import socket, time
TCP_IP = "192.168.1.2" # The IP address being connected to
TCP_PORT = 8888 # The socket being connected to
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.connect((self.TCP_IP, self.TCP_PORT))
time.sleep(.5)
while True:
s.send("Testing".encode()) # Sends a message
time.sleep(.5)
data = s.recv(64) # Recieves up to 64 bytes, can be more
print("recieved:", data)
time.sleep(.5)
s.close()