파이썬 소켓 프로그래밍 - 클라이언트/서버 예제
출처: https://webnautes.tistory.com/1381
서버를 먼저 실행하고, 클라인터를 실행하여 테스트 합니다.
(윈도우즈에서는 cmd 창을 두 개 실행해서 테스트합니다.)
# multiconn-server.py
import socket
from _thread import *
# 쓰레드에서 실행되는 코드: 접속 클라이언트마다 새 쓰레드가 생성되어 통신
def threaded(client_socket, addr):
print('Connected by :', addr[0], ':', addr[1])
while True:
try:
# 데이터가 수신되면 클라이언트에 다시 전송(에코)
data = client_socket.recv(1024)
if not data:
print('Disconnected by ' + addr[0],':',addr[1])
break
print('Received from ' + addr[0],':',addr[1] , data.decode())
client_socket.send(data)
except ConnectionResetError as e:
print('Disconnected by ' + addr[0],':',addr[1])
break
client_socket.close()
HOST = '127.0.0.1'
PORT = 9999
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen()
print('start server!')
# 클라이언트가 접속하면 accept 함수에서 새로운 소켓을 리턴
# 새 쓰레드에서 해당 소켓을 사용하여 통신
while True:
print('waiting...')
client_socket, addr = server_socket.accept()
start_new_thread(threaded, (client_socket, addr))
server_socket.close()
# multiconn-client.py
import socket
HOST = '127.0.0.1'
PORT = 9999
client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
# 클라이언트 문자열을 서버로 전송 후, 서버에서 돌려준 메시지를 화면에 출력
# 'quit' 입력할 때까지 반복
while True:
message = input('Enter Message(exit: "quit") : ').rstrip()
if message == 'quit':
break
if message == "":
message = "What?"
client_socket.send(message.encode())
data = client_socket.recv(1024)
print('Received from the server :', repr(data.decode()))
print("Goodby!")
client_socket.close()
'Python 활용' 카테고리의 다른 글
python, 프로그램(프로세스) 실행 확인 및 PID 검사 예제 (0) | 2022.05.10 |
---|---|
파이썬, faiss를 Windows에 설치하기 (0) | 2022.02.15 |
파이썬, 항목 유사도 검사 (0) | 2022.02.11 |
Python , GPU 모니터링 GPUtil 예제 (0) | 2022.02.10 |
파이썬, Parallel HTTP requests (requests_futures 이용) (0) | 2022.01.30 |