Socket Programming-> 클라이언트/서버 연결해주는 프로그램.
클라리언트는 메세지를 전달하고 받는 주체
서버는 클라이언트가 보내는 데이터로 작업하는 리스너(수동적인 주체)
Thread -> 기존 프로세스보다 좀더 가볍게 메모리 오버헤드를 사용하는 분할된 프로세스
Multi-threading -> 여러개 스레드를 "하나의 프로세스"에서 동시에 실행시키는 작업(프로세스)
Multi-threading Socket Programming -> 소켓연결을 멀티스레딩으로 구현해놓은 프로그램
Multi-threading Modules :파이썬은_thread 과 threading 모듈로 멀티스레딩구현함
(동기화와 스레드LOCK 가능함)
*스레드 락
- 락 : lock.acquire()
- 언락 : lock.release()
*스레드 생성 : thread.start_new_thread
from _thread import *
import threading
lock = threading.Lock()
# Server
# import socket programming library
import socket
# import thread module
from _thread import *
import threading
print_lock = threading.Lock()
# thread function
def threaded(c):
while True:
# data received from client
data = c.recv(1024)
if not data:
print('Bye')
# lock released on exit
print_lock.release()
break
# reverse the given string from client
data = data[::-1]
# send back reversed string to client
c.send(data)
# connection closed
c.close()
def Main():
host = ""
# reverse a port on your computer
# in our case it is 12345 but it
# can be anything
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("socket binded to port", port)
# put the socket into listening mode
s.listen(5)
print("socket is listening")
# a forever loop until client wants to exit
while True:
# establish connection with client
c, addr = s.accept()
# lock acquired by client
print_lock.acquire()
print('Connected to :', addr[0], ':', addr[1])
# Start a new thread and return its identifier
start_new_thread(threaded, (c,))
s.close()
if __name__ == '__main__':
Main()
# Client
# Import socket module
import socket
def Main():
# local host IP '127.0.0.1'
host = '127.0.0.1'
# Define the port on which you want to connect
port = 12345
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# connect to server on local computer
s.connect((host,port))
# message you send to server
message = "shaurya says geeksforgeeks"
while True:
# message sent to server
s.send(message.encode('ascii'))
# messaga received from server
data = s.recv(1024)
# print the received message
# here it would be a reverse of sent message
print('Received from the server :',str(data.decode('ascii')))
# ask the client whether he wants to continue
ans = input('\nDo you want to continue(y/n) :')
if ans == 'y':
continue
else:
break
# close the connection
s.close()
if __name__ == '__main__':
Main()
https://www.google.com/amp/s/www.geeksforgeeks.org/socket-programming-multi-threading-python/amp/
'Developing.. > Python' 카테고리의 다른 글
python --config ..설정값 관리하기! (0) | 2022.06.09 |
---|---|
Concurrency in python +GIL (0) | 2021.02.09 |
Projects in Python - price notifications (0) | 2021.02.05 |
Testing in Python (0) | 2021.02.05 |
Optimization in Python - Linear Programming (0) | 2021.02.05 |