본문 바로가기

python

socket, thread - 채팅 서버와 클라이언트

 

프롬포트에 netstat -ano | findstr :포트번호를 입력해서 사용중인 포트를 확인할 수 있다.

예시에서는 netstat -ano | findstr :5000

 

chatserver

멀티 채팅 서버 프로그램 기본 구조

주석 바인딩 주소는 로컬, 사용한 바인딩 주소는 ipconfig로 확인한 주소이다.

# 멀티 채팅 서버 프로그램 - socket + thread
import socket
import threading

ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# ss.bind(('127.0.0.1', 5000))
ss.bind(('192.168.0.75', 5000))
ss.listen(5)
print('채팅 서버 서비스 시작...')

users = []

# thread 처리 함수
def chatUser(conn):
    name = conn.recv(1024)
    data = '^^ ' + name.decode('utf-8') + '님 입장 ^^'
    print(data)
    try:
        for p in users:
            p.send(data.encode('utf-8'))
        
        while True:
            msg = conn.recv(1024)
            if not msg:continue
            data = name.decode('utf-8') + '님 메시지:' + msg.decode('utf-8')
            print('수신 내용 : ', data)  
            for p in users:  
                p.send(data.encode('utf-8'))
    except:
        # 유저 이탈시 오류 해결
        users.remove(conn)
        data = '~~ ' + name.decode('utf-8') + '님 퇴장 ~~'
        print(data)
        if users:
            for p in users:
                p.send(data.encode('utf-8'))
        else:
            print('사용자가 없습니다.')
    
    
while True:
    conn, addr = ss.accept()
    users.append(conn)    # 클라이언트를 저장
    th = threading.Thread(target=chatUser, args=(conn,))
    th.start()

 

chatclient

채팅 클라이언트 기본구조

 

버퍼링

정보의 송수신을 원활하게 하기 위해 정보를 일시적으로 저장하여 작업 처리 속도의 차이를 흡수하는 방법. 동영상 파일을 구현하는  네트워크의 상황에 따라 동영상이 끊어지는 현상이 발생할 , 일시적으로 데이터를 기억해 내어 다음 데이터와 원활하게 연결시켜 준다.

출처 : 고려대 한국어대사전

 

# 채팅 클라이언트

import socket
import threading
import sys

def handle(socket):
    while True:
        data = socket.recv(1024)
        if not data:continue
        print(data.decode('utf-8'))

# 파이썬의 표준출력은 버퍼링이 되는데 이때 버퍼를 비우기
sys.stdout.flush()

name = input('채팅 아이디 입력:')
cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# cs.connect(('127.0.0.1', 5000))
cs.connect(('192.168.0.75', 5000))
cs.send(name.encode('utf_8'))

th = threading.Thread(target=handle, args=(cs, ))
th.start()

while True:
    msg = input()
    sys.stdout.flush()
    if not msg:continue
    cs.send(msg.encode('utf_8'))
    
cs.close()

 

 

Aanaconda Prompt에서 채팅 기능 실행해보기

 

위치이동

cd C:\work\psou\pro1\pack4

서버 프로그램

python chatserver.py

클라이언트 프로그램

python chatclient.py

 

'python' 카테고리의 다른 글

웹 크롤링 - 미완성  (1) 2022.10.13
thread - pull, process  (0) 2022.10.13
thread - lock (빵 공장 예제)  (0) 2022.10.13
thread - 동기화(줄서기),lock을 활용한 전역변수 충돌 해결  (0) 2022.10.13
thread 예시 (시계)  (0) 2022.10.13