라즈베리파이 - 파이썬 서버
#python3 import socket import sys HOST = '' #all available interfaces PORT = 8888 #1. open Socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print ('Socket created') #2. bind to a address and port try: s.bind((HOST, PORT)) except socket.error as msg: print ('Bind Failed. Error code: ' + str(msg[0]) + ' Message: ' + msg[1]) sys.exit() print ('Socket bind complete') #3. Listen for incoming connections s.listen(10) print ('Socket now listening') #keep talking with the client while 1: #4. Accept connection conn, addr = s.accept() print ('Connected with ' + addr[0] + ':' + str(addr[1])) #5. Read/Send data = conn.recv(1024) if not data: break conn.sendall(data) print(data.decode()) conn.close() s.close()
PC 파이썬 클라이언트 코드
#python3 import socket HOST = 'server-ip' PORT = 8888 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) msg=input() s.send(msg.encode(encoding='utf_8', errors='strict')) data = s.recv(1024) print ('result: ' + data.decode()) s.close()
간단한 데이터를 주고 받을 수 있게 되었다.그런데 중요한 안드로이드와의 소켓통신은 어떻게 하나...