본문 바로가기

Python/Basic

[파이썬] 소켓프로그래밍-간단한 채팅프로그램 구현

import socket
import threading

# 서버 소켓 생성 및 바인딩
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ss.bind(('192.168.0.26', 5555))  # 서버의 IP 주소와 포트를 지정합니다.
ss.listen(5)  # 클라이언트의 연결 요청을 기다립니다.
print('채팅 서버 서비스 중........')
users = []  # 연결된 클라이언트들을 저장할 리스트

# 클라이언트와 채팅을 수행하는 함수
def chatUser(conn):
    name = conn.recv(1024)  # 클라이언트로부터 이름을 받아옵니다.
    data = '^^ ' + name.decode('utf-8') + '님 입장'
    print(data)

    try:
        for u in users:
            u.send(data.encode('utf-8'))

        # 채팅 수행
        while True:
            msg = conn.recv(1024)
            if not msg:
                continue
            cdata = name.decode('utf-8') + '님의 메세지:' + msg.decode('utf-8')
            print('수신 자료 : ', cdata)
            for u in users:
                u.send(cdata.encode('utf-8'))

    except:
        users.remove(conn)
        data = 'ㅠㅠ ' + name.decode('utf-8') + '님 퇴장'
        print(data)
        if users:
            for u in users:
                u.send(data.encode('utf-8'))
        else:
            print(exit())

# 서버가 클라이언트의 연결을 수락합니다.
while True:
    conn, addr = ss.accept()
    users.append(conn)  # 연결된 클라이언트를 리스트에 추가합니다.
    th = threading.Thread(target=chatUser, args=(conn,))
    th.start()  # 클라이언트와

서버측

 

 

 

import socket
import threading

# 서버 소켓 생성 및 바인딩
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ss.bind(('192.168.0.26', 5555))  # 서버의 IP 주소와 포트를 지정합니다.
ss.listen(5)  # 클라이언트의 연결 요청을 기다립니다.
print('채팅 서버 서비스 중........')
users = []  # 연결된 클라이언트들을 저장할 리스트

# 클라이언트와 채팅을 수행하는 함수
def chatUser(conn):
    name = conn.recv(1024)  # 클라이언트로부터 이름을 받아옵니다.
    data = '^^ ' + name.decode('utf-8') + '님 입장'
    print(data)

    try:
        for u in users:
            u.send(data.encode('utf-8'))

        # 채팅 수행
        while True:
            msg = conn.recv(1024)
            if not msg:
                continue
            cdata = name.decode('utf-8') + '님의 메세지:' + msg.decode('utf-8')
            print('수신 자료 : ', cdata)
            for u in users:
                u.send(cdata.encode('utf-8'))

    except:
        users.remove(conn)
        data = 'ㅠㅠ ' + name.decode('utf-8') + '님 퇴장'
        print(data)
        if users:
            for u in users:
                u.send(data.encode('utf-8'))
        else:
            print(exit())

# 서버가 클라이언트의 연결을 수락합니다.
while True:
    conn, addr = ss.accept()
    users.append(conn)  # 연결된 클라이언트를 리스트에 추가합니다.
    th = threading.Thread(target=chatUser, args=(conn,))
    th.start()  # 클라이언트와 채팅을 수행하는 스레드를 시작합니다.

클라이언트측

 

 

위 코드를 이용하여 프롬프트에서 구현한 멀티 채팅창

 

 

 

 

 

 

 

소켓과 스레드에 대한 개념은 밑의 내용들을 참고하시면 되세요!


 

https://soocorn.tistory.com/entry/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%86%8C%EC%BC%93

 

[파이썬] Socket(소켓)

소켓이란? 소켓은 프로그램과 운영 체제 간의 인터페이스 역할을 합니다. 프로그램에서 소켓 작업을 요청하면, 운영 체제는 그 요청을 받아들여 새로운 소켓을 생성합니다. 이 소켓을 통해서만

soocorn.tistory.com

 

 

https://soocorn.tistory.com/entry/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%8A%A4%EB%A0%88%EB%93%9C

 

[파이썬] Thread(스레드)

스레드란? 쓰레드(Thread)는 프로그램이 동작할 때, 동시에 여러 작업을 수행할 수 있게 해주는 중요한 개념입니다. 이는 파이썬뿐만 아니라 모든 프로그래밍 언어에서 중요한 개념으로 사용됩니

soocorn.tistory.com