2025년, 코딩은 선택이 아닌 필수!

2025년 모든 학교에서 코딩이 시작 됩니다. 먼저 준비하는 사람만이 기술을 선도해 갑니다~

강의자료/C#

[C#] 멀티채팅 프로그램 - 서버편

원당컴1 2021. 3. 10. 20:59
목표

- 소켓통신 방법을 살펴 봅니다.

- 서버와 클라이언트 프로그램의 의미를 이해 합니다.

- 서버의 역할은 클라이언트의 중계역할을 담당하며 24시간 365일 구동 되는 것을 목표로 하며 안정성이 최우선됨(클라이언트 접속/해제 시에 메모리 생성 및 해제)

 

서버 소켓 프로그래밍 구현 방법 이해하기

1. 서버 소켓 생성하기 : Socket Create

2. 서버가 사용할 IP 주소와 포트번호를 결합 : Bind

3. 서버 소켓 시작 : Start

4. 클라이언트로 부터 연결요청이 들어 오는지 확인 : Listen

5. 연결요청 시 허용 : accept

6. 클라이언트로부터 정보 수신 : Received

7. 클라이언트 접속 해제 처리 : DisConnected

 

 

폼구성

panel : 1개 , Dock - Top

label : 1개 (접속대기포트)

textbox : 1개 (1004)

button : 1개 (연결대기)

richtextbox : 1개, Dock - Fill

 

 

SeverSocket 소스

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
 
namespace MultiChatServer
{
    internal class Client : SocketAsyncEventArgs
    {
        // 메시지는 개행으로 구분한다.
        private static char CR = (char)0x0D;
        private static char LF = (char)0x0A;
        private Socket socket;
        // 메시지를 모으기 위한 버퍼
        private StringBuilder sb = new StringBuilder();
        private IPEndPoint remoteAddr;
 
        public delegate void ClientReceiveHandler(Socket sock, String msg); //수신 메시지 이벤트를 위한 델리게이트
        public event ClientReceiveHandler OnReceive;
        public delegate void ClientDisconnectHandler(Socket sock);
        public event ClientDisconnectHandler OnDisconnect;
 
        public Client(Socket socket)
        {
            try
            {
                this.socket = socket;
                // 메모리 버퍼를 초기화 한다. 크기는 1024이다
                base.SetBuffer(new byte[1024], 01024);
                base.UserToken = socket;
                // 메시지가 오면 이벤트를 발생시킨다. (IOCP로 꺼내는 것)
                base.Completed += Client_Completed;
                // 메시지가 오면 이벤트를 발생시킨다. (IOCP로 넣는 것)
                this.socket.ReceiveAsync(this);
                // 접속 환영 메시지
                remoteAddr = (IPEndPoint)socket.RemoteEndPoint;
                if(remoteAddr!=null)
                {
                    Console.WriteLine($"Client : (From: {remoteAddr.Address.ToString()}:{remoteAddr.Port}, Connection time: {DateTime.Now})");
                    this.Send("Welcome server!\r\n>");
                }
                
            }
            catch(Exception e)
            {
                return;
            }
            
        }
        ~Client()
        {
            socket = null;
        }
 
        public void Send(String msg)
        {
            byte[] sendData = Encoding.Unicode.GetBytes(msg);
            //sendArgs.SetBuffer(sendData, 0, sendData.Length);
            //socket.SendAsync(sendArgs);
            // Client로 메시지 전송
            if(socket != null)     socket.Send(sendData, sendData.Length, SocketFlags.None);
        }
 
        private void Client_Completed(object sender, SocketAsyncEventArgs e)
        {
            // 접속이 연결되어 있으면...
            if (socket.Connected && base.BytesTransferred > 0)
            {
                // 수신 데이터는 e.Buffer에 있다.
                byte[] data = e.Buffer;
                // 데이터를 string으로 변환한다.
                string msg = Encoding.Unicode.GetString(data);
                // 메모리 버퍼를 초기화 한다. 크기는 1024이다
                base.SetBuffer(new byte[1024], 01024);
                // 버퍼의 공백은 없앤다.
                sb.Append(msg.Trim('\0'));
                // 메시지의 끝이 이스케이프 \r\n의 형태이면 서버에 표시한다.
                if (sb.Length >= 2 && sb[sb.Length - 2== CR && sb[sb.Length - 1== LF)
                {
                    // 개행은 없애고..
                    sb.Length = sb.Length - 2;
                    // string으로 변환한다.
                    msg = sb.ToString();
                    if (OnReceive != null)
                        OnReceive(this.socket,msg); // 수신 이벤트 발생
 
                    
                    // 만약 메시지가 exit이면 접속을 끊는다.
                    if ("exit".Equals(msg, StringComparison.OrdinalIgnoreCase))
                    {
                        OnDisconnect(socket);
                        // 접속을 중단한다.
                        socket.DisconnectAsync(this);
                        return;
                    }
                    // 버퍼를 비운다.
                    sb.Clear();
                }
                // 메시지가 오면 이벤트를 발생시킨다. (IOCP로 넣는 것)
                this.socket.ReceiveAsync(this);
            }
            else
            {
                OnDisconnect(socket);
                
}
        }
 
    }
 
    // 서버 Event로 SocketAsyncEventArgs를 상속받았다.
    class Server : SocketAsyncEventArgs
    {
        public delegate void ClientReceiveHandler(Socket sock, String msg); //수신 메시지 이벤트를 위한 델리게이트
        public event ClientReceiveHandler OnReceive;
        public delegate void ClientDisconnectHandler(Socket sock);
        public event ClientDisconnectHandler OnDisconnect;
        public delegate void ClientConnectHandler(Socket sock);
        public event ClientConnectHandler OnConnect;
 
        private Socket socket;
        public List<Socket> clientSocketList = new List<Socket>();//클라이언트 소켓을 관리하는 리스트, 소켓과 접속 아이디를 관리하자.
        public Dictionary<Socket,Client> clientList = new Dictionary<Socket, Client>();//클라이언트 소켓을 관리하는 리스트, 소켓과 접속 아이디를 관리하자.
 
        public Server(Socket socket)
        {
            this.socket = socket;
            base.UserToken = socket;
            // Client로부터 Accept이 되면 이벤트를 발생시킨다. (IOCP로 꺼내는 것)
            base.Completed += Server_Completed; 
        }
 
        public void SocketClose()
        {
            foreach(var client in clientSocketList)
            {
                if (client.Connected) client.Disconnect(false);
                client.Dispose();
            }
            foreach (var client in clientList)
            {
                Client c = client.Value;
                c.Dispose();
            }
            clientSocketList.Clear();
            clientList.Clear();
        }
 
        // Client가 접속하면 이벤트를 발생한다.
        private void Server_Completed(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                // 접속이 완료되면, Client Event를 생성하여 Receive이벤트를 생성한다.
                var client = new Client(e.AcceptSocket);
                client.OnReceive += ClientReceive;
                client.OnDisconnect += ClientDisconnect;
 
                clientSocketList.Add(e.AcceptSocket);
                clientList.Add(e.AcceptSocket, client);
                // 서버 Event에 cilent를 제거한다.
                e.AcceptSocket = null;
                // Client로부터 Accept이 되면 이벤트를 발생시킨다. (IOCP로 넣는 것)
                this.socket.AcceptAsync(e);
                if(OnConnect != null)
                {
                    OnConnect(this.socket);
                }
            }
            catch (Exception ex)
            {
                return;
            }
            
        }
 
        private void ClientDisconnect(Socket sock)
        {
            
            if (OnDisconnect != null)
                OnDisconnect(sock);
 
            clientList.Remove(sock);
            clientSocketList.Remove(sock);
        }
 
        private void ClientReceive(Socket sock, string msg)
        {
            if (OnReceive != null)
                OnReceive(sock, msg);
        }
        public void SendAllMessage(String msg)
        {
            foreach(var client in clientList)
            {
                Client c = client.Value;
                c.Send(msg);
            }
        }
    }
 
    class ServerProgram : Socket
    {
        public delegate void ClientReceiveHandler(Socket sock, String msg); //수신 메시지 이벤트를 위한 델리게이트
        public event ClientReceiveHandler OnReceive;
        public delegate void ClientDisconnectHandler(Socket sock);
        public event ClientDisconnectHandler OnDisconnect;
        public delegate void ClientConnectHandler(Socket sock);
        public event ClientConnectHandler OnConnect;
 
        private bool _disposed = false;
 
 
        public Server serverSocket;
        public IPEndPoint ipEndPoint;
        public ServerProgram(int port) : base(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        {
            ipEndPoint = new IPEndPoint(IPAddress.Any, port);
            try
            {
                base.Bind(ipEndPoint);
                base.Listen(20);
                // 비동기 소켓으로 Server 클래스를 선언한다. (IOCP로 집어넣는것)
                serverSocket = new Server(this);
                serverSocket.OnConnect += ClientConnect;
                serverSocket.OnDisconnect += ClientDisConnect;
                serverSocket.OnReceive += ClientRecieve;
 
                base.AcceptAsync(serverSocket);
            }
            catch(Exception ex)
            {
                return;
            }
            
        }
        
        private void ClientRecieve(Socket sock, string msg)
        {
            if (OnReceive != null)
                OnReceive(sock, msg);
        }
 
        private void ClientDisConnect(Socket sock)
        {
            if (OnDisconnect != null)
                OnDisconnect(sock);
        }
 
        private void ClientConnect(Socket sock)
        {
            if (OnConnect != null)
                OnConnect(sock);
        }
 
        protected override void Dispose(bool disposing)
        {
            if (_disposed) return;
            try
            {
                if(serverSocket != null)
                {
                    serverSocket.SocketClose();
                    base.Disconnect(true);
                    
                    base.Shutdown(SocketShutdown.Both);
                    base.Close();
                    base.Dispose();
 
                    GC.SuppressFinalize(serverSocket);
                }
                //serverSocket = null;
            }
            catch(Exception ex)
            {
                //
            }
            finally
            {
                //base.Close(0);
            }
            _disposed = true;
        }
 
        public void SendMessage(String msg)
        {
            if (serverSocket != null)
                serverSocket.SendAllMessage(msg);
        }
    }
 
}
cs

 

 

Form1 소스코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace MultiChatServer
{
    public partial class Form1 : Form
    {
 
        public Dictionary<Socket, string> clientSocketList = new Dictionary<Socket, string>();//클라이언트 소켓을 관리하는 리스트, 소켓과 접속 아이디를 관리하자.
 
        ServerProgram multiServer;
        int serverPort;
 
        public Form1() 
        {
            InitializeComponent();
 
        }
 
 
        private void allClientSend(string message, string username, bool flag)
        {
            String curDate = DateTime.Now.ToString("yyyy.MM.dd. HH:mm:ss"); // 현재 날짜 받기
 
            String sendMsg;
 
            byte[] buffer = null;
            if (flag)
            {
                if (message.Equals("disConnect"))
                    sendMsg = username + " 님이 대화방을 나갔습니다.";
                else
                    sendMsg = "[ " + curDate + " ] " + username + " : " + message;
 
            }
            else
            {
 
                sendMsg = message;
 
            }
 
            multiServer.SendMessage(sendMsg);
 
 
        }
 
        private void displayMessage(string text)
        {
            if (txt_Message.InvokeRequired) //다른 쓰레드에서 실행되어 Invoke가 필요한 상태라면 
            {
                txt_Message.BeginInvoke(new MethodInvoker(delegate   ///델리게이트로 넘겨서 실행
                {
                    txt_Message.AppendText(text + Environment.NewLine);
                }));
            }
            else
                txt_Message.AppendText(text + Environment.NewLine);
 
        }
 
        private void button1_Click(object sender, EventArgs ev)
        {
            button1.Enabled = false;
            try
            {
                serverPort = Int32.Parse(txt_ServerPort.Text.ToString()); // 소켓 번호 설정
            }
            catch (FormatException e)
            {
                //textbox 에 숫자 외의 문자인 경우
                serverPort = 1004;
            }
 
            multiServer = new ServerProgram(serverPort);
            multiServer.OnConnect += clientConnected;
            multiServer.OnDisconnect += clientDisconncted;
            multiServer.OnReceive += clientReceive;               
            
        }
 
        private void clientReceive(Socket sock, String msg)
        {
            int index = msg.IndexOf("$");
            String curDate = DateTime.Now.ToString("HH:mm:ss"); // 현재 날짜 받기
            String stCmd="";
            String stData="";
            String sendMsg = "";
            if (index > 0)
            {
                stCmd = msg.Substring(0, index); //$를 기준으로 앞 부분을 cmd로 
                stData = msg.Substring(index + 1);
                
            }
            if(stCmd.ToUpper() =="Login".ToUpper())
            {
                clientSocketList[sock] = stData; // Login 사용자명 셋팅
                sendMsg = "[ " + curDate + " ] " + stData + "님이 입장하셨습니다.";
            }
            else
            {
                sendMsg = "[ " + curDate + " ] " + stCmd + " : " + stData;
            }
            displayMessage(sendMsg);
            if(multiServer!=null) multiServer.SendMessage(sendMsg);
 
        }
 
        private void clientDisconncted(Socket sock)
        {
            String userName;
            if (clientSocketList.ContainsKey(sock))
            {
                userName = clientSocketList[sock];
                allClientSend("disConnect", userName, true);
                clientSocketList.Remove(sock);
            }
        }
 
        private void clientConnected(Socket sock)
        {
            clientSocketList.Add(sock, "");
        }
    }
}
 
cs

 

활용

멀티 게임 서버 와 같이 중계 역할을 수행하는 서버 프로그램 구현

 

 

=====================================================

이 자료는 학생들과 특강시간에 만들어 보는 프로그램입니다.

=====================================================

 

오늘도 최선을 다하는 우리 학생들을 응원합니다.

인천 서구 검단신도시 원당컴퓨터학원

사업자 정보 표시
원당컴퓨터학원 | 기희경 | 인천 서구 당하동 1028-2 장원프라자 502호 | 사업자 등록번호 : 301-96-83080 | TEL : 032-565-5497 | Mail : icon001@naver.com | 통신판매신고번호 : 호 | 사이버몰의 이용약관 바로가기