-
C# ECHO 채팅서버 - 1:N 채팅을 위한 Thread, 서버 클래스 생성스마트팩토리 개발자 교육(23.05.08 ~ 23.10.27)7/네트워크 기초이론 2023. 5. 19. 17:21
1. N명의 클라이언트의 접속을 허용하기 위해 Client List를 만들고,
각 클라이언트 마다 메시지를 전달 받을 Listener를 만든다
public class Server { // 클라이언트들을 저장할 수 있는 어레이 리스트 List<TcpClient> clientList; // 클라이언트가 접속 할때 마다 만들 Listener TcpListener listener;2. 서버의 바인딩과 ip 주소를 생성시 만들어 준다
// 생성자 서버 실행시 public Server(IPAddress ip, int port) { clientList = new List<TcpClient>(); listener = new TcpListener(ip, port); listener.Start(); }3. 클라이언트 연결 요청을 대기하고 연결시 메시지를 전달 받을 Thread를 생성한다
// 클라이언트 연결을 처리하는 메소드 public void AcceptClient() { while (true) { Console.WriteLine("클라이언트 접속 대기중..."); TcpClient tcpClient = listener.AcceptTcpClient(); Console.WriteLine("클라이언트가 접속하였습니다..."); clientList.Add(tcpClient); // 클라이언트 접속시 클라이언트 마다 메시지를 받을 스레드를 생성 Thread receiveThread = new Thread(() => this.Receive(tcpClient)); receiveThread.Start(); } }4. 클라이언트에게 메시지를 받으면 다른 클라이언트들에게 받은 메시지를 전달해준다
// 클라이언트에게 메시지를 받고 다른 클라이언트들에게 메시지를 받는다 public void Receive(TcpClient currentClient) { while (true) { byte[] buffer = new byte[1024]; NetworkStream stream = currentClient.GetStream(); int nbytes; string msg = ""; while ((nbytes = stream.Read(buffer, 0, buffer.Length)) > 0) { msg = Encoding.UTF8.GetString(buffer, 0, nbytes); Console.WriteLine(msg); for (int i = 0; i < clientList.Count; i++) { byte[] buff = Encoding.UTF8.GetBytes(msg); NetworkStream other = ((TcpClient)clientList[i]).GetStream(); other.Write(buff, 0, buff.Length); } } } }*main 코드
static void Main(string[] args) { IPAddress ip = IPAddress.Parse("0.0.0.0"); int port = 9876; Server myServer = new Server(ip, port); Thread acceptClientThread = new Thread(myServer.AcceptClient); acceptClientThread.Start(); while (true) { }; }*추가해야될 사항 : 클라이언트의 접속 종료 처리
'스마트팩토리 개발자 교육(23.05.08 ~ 23.10.27)7 > 네트워크 기초이론' 카테고리의 다른 글
C# ECHO 채팅서버 - 1:N 채팅을 위한 Thread, Client 클래스 생성 (0) 2023.05.19 C# ECHO 채팅서버 - 서버가 메시지 보내기 (0) 2023.05.18 C# - ECHO 채팅 서버 - 클라이언트 코드 (0) 2023.05.18 C# - ECHO 채팅 서버 - Server 코드 (0) 2023.05.18 NAT, 포트 포워딩, DNS (0) 2023.05.11