■ NetworkComms.Net을 사용해 채팅 프로그램을 만드는 방법을 보여준다.
▶ MainWindow.xaml
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 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="600" Title="NetworkComms.Net을 사용해 채팅 프로그램 만들기" Background="#ff7ca0ff" FontFamily="나눔고딕코딩" FontSize="16"> <Grid Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid Grid.Row="0" Margin="10"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Label Grid.Column="0" VerticalAlignment="Center" Content="서버 IP :" /> <TextBox Name="serverIPTextBox" Grid.Column="1" VerticalAlignment="Center" Width="100" Height="25" VerticalContentAlignment="Center" /> <Label Grid.Column="2" VerticalAlignment="Center" Content="서버 포트 :" /> <TextBox Name="serverPortTextBox" Grid.Column="3" VerticalAlignment="Center" Width="50" Height="25" VerticalContentAlignment="Center" /> <Label Grid.Column="5" VerticalAlignment="Center" Content="로컬명 : " /> <TextBox Name="localNameTextBox" Grid.Column="6" Width="100" Height="25" VerticalContentAlignment="Center" /> </Grid> <Grid Grid.Row="1"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Grid Name="chatGrid" Grid.Column="0" Margin="5 0 5 0"> <ScrollViewer Name ="chatMessageScrollViewer"> <TextBlock Name="chatMessageTextBlock" Background="White" TextWrapping="Wrap" /> </ScrollViewer> </Grid> <Grid Grid.Column="1"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <CheckBox Name="enableLocalServerCheckBox" Grid.Row="0" HorizontalAlignment="Left" Margin="5" Content="로컬 서버 활성화" /> <Label Grid.Row="1" Content="연결 방법 :" HorizontalAlignment="Left" Margin="5" /> <StackPanel Grid.Row="2" Margin="5" Orientation="Horizontal"> <RadioButton Name="tcpRadioButton" Grid.Column="0" Content="TCP" IsChecked="True" /> <RadioButton Name="udpRadioButton" Grid.Column="1" Margin="5 0 0 0" Content="UDP" /> </StackPanel> <Label Grid.Row="3" Content="직렬화 방법 :" HorizontalAlignment="Left" Margin="5" /> <StackPanel Grid.Row="4" Margin="5" Orientation="Horizontal"> <RadioButton Name="protobufRadiobButton" Grid.Column="0" Content="Protobuf" IsChecked="True" /> <RadioButton Name="jsonRadioButton" Grid.Column="1" Margin="5 0 0 0" Content="JSON" /> </StackPanel> <CheckBox Name="useEncryptionCheckBox" Grid.Row="5" HorizontalAlignment="Left" Margin="5" Content="암호화 사용" /> <Grid Grid.Row="6"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Label Grid.Row="0" Content="메시지 송신자 :" HorizontalAlignment="Left" Margin="5" /> <TextBox Name="messageSenderTextBox" Grid.Row="1" Margin="5 5 5 0" IsReadOnly="True" VerticalScrollBarVisibility="Auto" /> </Grid> </Grid> </Grid> <Grid Grid.Row="2"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Label Grid.Column="0" VerticalAlignment="Center" Margin="5" Content="메시지 :" /> <TextBox Name="messageTextBox" Grid.Column="1" VerticalAlignment="Center" Height="25" VerticalContentAlignment="Center" /> <Button Name="sendMessageButton" Grid.Column="2" VerticalAlignment="Center" Margin="5" Width="80" Height="25" Content="전송" /> </Grid> </Grid> </Window> |
▶ MainWindow.xaml.cs
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 |
using System.ComponentModel; using System.Windows; using System.Windows.Input; using NetworkCommsDotNet; using NetworkCommsDotNet.Connections; using NetworkCommsDotNet.DPSBase; using NetworkCommsDotNet.Tools; namespace TestProject { /// <summary> /// 메인 윈도우 /// </summary> public partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 채팅 서버 /// </summary> private ChatServer charServer; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { InitializeComponent(); this.localNameTextBox.Text = HostInfo.HostName; this.charServer = new ChatServer ( this.chatMessageTextBlock, this.chatMessageScrollViewer, this.messageSenderTextBox, this.messageTextBox ); this.charServer.PrintUsageInstructions(); this.charServer.RefreshConfiguration(); Closing += Window_Closing; this.serverIPTextBox.LostFocus += serverIPTextBox_LostFocus; this.serverPortTextBox.LostFocus += serverPortTextBox_LostFocus; this.localNameTextBox.LostFocus += localNameTextBox_LostFocus; this.enableLocalServerCheckBox.Checked += enableLocalServerCheckBox_Checked; this.enableLocalServerCheckBox.Unchecked += enableLocalServerCheckBox_Checked; this.tcpRadioButton.Checked += tcpRadioButton_Checked; this.udpRadioButton.Checked += udpRadioButton_Checked; this.protobufRadiobButton.Checked += protobufRadiobButton_Checked; this.jsonRadioButton.Checked += jsonRadioButton_Checked; this.useEncryptionCheckBox.Checked += useEncryptionCheckBox_Checked; this.useEncryptionCheckBox.Unchecked += useEncryptionCheckBox_Checked; this.messageTextBox.KeyUp += messageTextBox_KeyUp; this.sendMessageButton.Click += sendMessageButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 윈도우 닫을 경우 처리하기 - Window_Closing(sender, e) /// <summary> /// 윈도우 닫을 경우 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Window_Closing(object sender, CancelEventArgs e) { NetworkComms.Shutdown(); } #endregion #region 서버 IP 텍스트 박스 포커스 상실시 처리하기 - serverIPTextBox_LostFocus(sender, e) /// <summary> /// 서버 IP 텍스트 박스 포커스 상실시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void serverIPTextBox_LostFocus(object sender, RoutedEventArgs e) { this.charServer.ServerIPAddress = this.serverIPTextBox.Text.Trim(); } #endregion #region 서버 포트 텍스트 박스 포커스 상실시 처리하기 - serverPortTextBox_LostFocus(sender, e) /// <summary> /// 서버 포트 텍스트 박스 포커스 상실시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void serverPortTextBox_LostFocus(object sender, RoutedEventArgs e) { int portNumber; if(int.TryParse(this.serverPortTextBox.Text, out portNumber)) { this.charServer.ServerPort = portNumber; } else { this.serverPortTextBox.Text = string.Empty; } } #endregion #region 로컬명 텍스트 박스 포커스 상실시 처리하기 - localNameTextBox_LostFocus(sender, e) /// <summary> /// 로컬명 텍스트 박스 포커스 상실시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void localNameTextBox_LostFocus(object sender, RoutedEventArgs e) { this.charServer.LocalName = this.localNameTextBox.Text.Trim(); } #endregion #region 로컬 서버 활성화 체크 박스 체크시 처리하기 - enableLocalServerCheckBox_Checked(sender, e) /// <summary> /// 로컬 서버 활성화 체크 박스 체크시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void enableLocalServerCheckBox_Checked(object sender, RoutedEventArgs e) { this.charServer.LocalServerEnabled = (bool)enableLocalServerCheckBox.IsChecked; this.charServer.RefreshConfiguration(); this.protobufRadiobButton.IsEnabled = !this.charServer.LocalServerEnabled; this.jsonRadioButton.IsEnabled = !this.charServer.LocalServerEnabled; } #endregion #region TCP 라디오 버튼 체크시 처리하기 - tcpRadioButton_Checked(sender, e) /// <summary> /// TCP 라디오 버튼 체크시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void tcpRadioButton_Checked(object sender, RoutedEventArgs e) { if(this.udpRadioButton != null && this.udpRadioButton.IsChecked != null && !(bool)this.udpRadioButton.IsChecked) { this.tcpRadioButton.IsChecked = true; this.udpRadioButton.IsChecked = false; this.charServer.ConnectionType = ConnectionType.TCP; this.charServer.RefreshConfiguration(); } } #endregion #region UDP 라디오 버튼 체크시 처리하기 - udpRadioButton_Checked(sender, e) /// <summary> /// UDP 라디오 버튼 체크시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void udpRadioButton_Checked(object sender, RoutedEventArgs e) { if(this.tcpRadioButton != null && this.tcpRadioButton.IsChecked != null && !(bool)this.tcpRadioButton.IsChecked) { this.tcpRadioButton.IsChecked = false; this.udpRadioButton.IsChecked = true; this.charServer.ConnectionType = ConnectionType.UDP; this.charServer.RefreshConfiguration(); } } #endregion #region Protobuf 라디오 버튼 체크시 처리하기 - protobufRadiobButton_Checked(sender, e) /// <summary> /// Protobuf 라디오 버튼 체크시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void protobufRadiobButton_Checked(object sender, RoutedEventArgs e) { if(this.jsonRadioButton != null && this.jsonRadioButton.IsChecked != null && !(bool)this.jsonRadioButton.IsChecked) { this.protobufRadiobButton.IsChecked = true; this.jsonRadioButton.IsChecked = false; this.charServer.DataSerializer = DPSManager.GetDataSerializer<ProtobufSerializer>(); this.charServer.RefreshConfiguration(); this.charServer.AppendLineToChatHistory("데이터 직렬화기가 Protobuf 직렬화기로 변경되었습니다."); } } #endregion #region JSON 라디오 버튼 체크시 처리하기 - jsonRadioButton_Checked(sender, e) /// <summary> /// JSON 라디오 버튼 체크시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void jsonRadioButton_Checked(object sender, RoutedEventArgs e) { if ( this.protobufRadiobButton != null && this.protobufRadiobButton.IsChecked != null && !(bool)this.protobufRadiobButton.IsChecked ) { this.protobufRadiobButton.IsChecked = false; this.jsonRadioButton.IsChecked = true; this.charServer.DataSerializer = DPSManager.GetDataSerializer<JSONSerializer>(); this.charServer.RefreshConfiguration(); this.charServer.AppendLineToChatHistory("데이터 직렬화기가 JSON 직렬화기로 변경되었습니다."); } } #endregion #region 암호화 사용 체크 박스 체크시 처리하기 - useEncryptionCheckBox_Checked(sender, e) /// <summary> /// 암호화 사용 체크 박스 체크시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void useEncryptionCheckBox_Checked(object sender, RoutedEventArgs e) { this.charServer.EncryptionEnabled = (bool)useEncryptionCheckBox.IsChecked; this.charServer.RefreshConfiguration(); } #endregion #region 메시지 텍스트 박스 키 UP시 처리하기 - messageTextBox_KeyUp(sender, e) /// <summary> /// 메시지 텍스트 박스 키 UP시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void messageTextBox_KeyUp(object sender, KeyEventArgs e) { if(e.Key == Key.Enter || e.Key == Key.Return) { this.charServer.SendMessage(this.messageTextBox.Text); } } #endregion #region 메시지 발송 버튼 클릭시 처리하기 - sendMessageButton_Click(sender, e) /// <summary> /// 메시지 발송 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void sendMessageButton_Click(object sender, RoutedEventArgs e) { this.charServer.SendMessage(messageTextBox.Text); } #endregion } } |
▶ ChatMessage.cs
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 |
using System; using System.Collections.Generic; using System.IO; using System.Text; using Newtonsoft.Json; using ProtoBuf; using NetworkCommsDotNet.DPSBase; using NetworkCommsDotNet.Tools; namespace TestProject { /// <summary> /// 채팅 메시지 /// </summary> [ProtoContract] [JsonObject(MemberSerialization.OptIn)] public class ChatMessage : IExplicitlySerialize { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 소스 식별자 /// </summary> [ProtoMember(1)] [JsonProperty] private string sourceIdentifier; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 소스 식별자 - SourceIdentifier /// <summary> /// 소스 식별자 /// </summary> public ShortGuid SourceIdentifier { get { return new ShortGuid(this.sourceIdentifier); } } #endregion #region 소스명 - SourceName /// <summary> /// 소스명 /// </summary> [ProtoMember(2)] [JsonProperty] public string SourceName { get; private set; } #endregion #region 메시지 - Message /// <summary> /// 메시지 /// </summary> [ProtoMember(3)] [JsonProperty] public string Message { get; private set; } #endregion #region 메시지 인덱스 - MessageIndex /// <summary> /// 메시지 인덱스 /// </summary> [ProtoMember(4)] [JsonProperty] public long MessageIndex { get; private set; } #endregion #region 릴레이 카운트 - RelayCount /// <summary> /// 릴레이 카운트 /// </summary> [ProtoMember(5)] [JsonProperty] public int RelayCount { get; private set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Private #region 생성자 - ChatMessage() /// <summary> /// 생성자 /// </summary> private ChatMessage() { } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ChatMessage(sourceIdentifier, sourceName, message, messageIndex) /// <summary> /// 생성자 /// </summary> /// <param name="sourceIdentifier">소스 식별자</param> /// <param name="sourceName">소스명</param> /// <param name="message">메시지</param> /// <param name="messageIndex">메시지 인덱스</param> public ChatMessage(ShortGuid sourceIdentifier, string sourceName, string message, long messageIndex) { this.sourceIdentifier = sourceIdentifier; SourceName = sourceName; Message = message; MessageIndex = messageIndex; RelayCount = 0; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 역직렬화하기 - Deserialize(inputStream, chatMessage) /// <summary> /// 역직렬화하기 /// </summary> /// <param name="inputStream">입력 스트림</param> /// <param name="chatMessage">채팅 메시지</param> public static void Deserialize(Stream inputStream, out ChatMessage chatMessage) { chatMessage = new ChatMessage(); chatMessage.Deserialize(inputStream); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 릴레이 카운트 증가시키기 - IncrementRelayCount() /// <summary> /// 릴레이 카운트 증가시키기 /// </summary> public void IncrementRelayCount() { RelayCount++; } #endregion #region 직렬화하기 - Serialize(outputStream) /// <summary> /// 직렬화 하기 /// </summary> /// <param name="outputStream">출력 스트림</param> public void Serialize(Stream outputStream) { List<byte[]> byteArrayList = new List<byte[]>(); byte[] sourceIdentifierByteArray = Encoding.UTF8.GetBytes(this.sourceIdentifier); byte[] sourceIdentifierLengthByteArray = BitConverter.GetBytes(sourceIdentifierByteArray.Length); byteArrayList.Add(sourceIdentifierLengthByteArray); byteArrayList.Add(sourceIdentifierByteArray); byte[] sourceNameByteArray = Encoding.UTF8.GetBytes(SourceName); byte[] sourceNameLengthByteArray = BitConverter.GetBytes(sourceNameByteArray.Length); byteArrayList.Add(sourceNameLengthByteArray); byteArrayList.Add(sourceNameByteArray); byte[] messageByteArray = Encoding.UTF8.GetBytes(Message); byte[] messageLengthByteArray = BitConverter.GetBytes(messageByteArray.Length); byteArrayList.Add(messageLengthByteArray); byteArrayList.Add(messageByteArray); byte[] messageIndexByteArray = BitConverter.GetBytes(MessageIndex); byteArrayList.Add(messageIndexByteArray); byte[] relayCountByteArray = BitConverter.GetBytes(RelayCount); byteArrayList.Add(relayCountByteArray); foreach(byte[] byteArray in byteArrayList) { outputStream.Write(byteArray, 0, byteArray.Length); } } #endregion #region 역직렬화하기 - Deserialize(inputStream) /// <summary> /// 역직렬화하기 /// </summary> /// <param name="inputStream">입력 스트림</param> public void Deserialize(Stream inputStream) { byte[] sourceIdentifierLengthByteArray = new byte[sizeof(int)]; inputStream.Read(sourceIdentifierLengthByteArray, 0, sizeof(int)); byte[] sourceIdentifierByteArray = new byte[BitConverter.ToInt32(sourceIdentifierLengthByteArray, 0)]; inputStream.Read(sourceIdentifierByteArray, 0, sourceIdentifierByteArray.Length); this.sourceIdentifier = new string(Encoding.UTF8.GetChars(sourceIdentifierByteArray)); byte[] sourceNameLengthByteArray = new byte[sizeof(int)]; inputStream.Read(sourceNameLengthByteArray, 0, sizeof(int)); byte[] sourceNameByteArray = new byte[BitConverter.ToInt32(sourceNameLengthByteArray, 0)]; inputStream.Read(sourceNameByteArray, 0, sourceNameByteArray.Length); SourceName = new String(Encoding.UTF8.GetChars(sourceNameByteArray)); byte[] messageLengthByteArray = new byte[sizeof(int)]; inputStream.Read(messageLengthByteArray, 0, sizeof(int)); byte[] messageByteArray = new byte[BitConverter.ToInt32(messageLengthByteArray, 0)]; inputStream.Read(messageByteArray, 0, messageByteArray.Length); Message = new string(Encoding.UTF8.GetChars(messageByteArray)); byte[] messageIndexByteArray = new byte[sizeof(long)]; inputStream.Read(messageIndexByteArray, 0, sizeof(long)); MessageIndex = BitConverter.ToInt64(messageIndexByteArray, 0); byte[] relayCountByteArray = new byte[sizeof(int)]; inputStream.Read(relayCountByteArray, 0, sizeof(int)); RelayCount = BitConverter.ToInt32(relayCountByteArray, 0); } #endregion } } |
▶ ChatServerBase.cs
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 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 |
using System; using System.Collections.Generic; using System.Linq; using System.Net; using NetworkCommsDotNet; using NetworkCommsDotNet.Connections; using NetworkCommsDotNet.Connections.TCP; using NetworkCommsDotNet.Connections.UDP; using NetworkCommsDotNet.DPSBase; using NetworkCommsDotNet.Tools; namespace TestProject { /// <summary> /// 채팅 서버 베이스 /// </summary> public abstract class ChatServerBase { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Protected #region Field /// <summary> /// 차트 메시지 딕셔너리 /// </summary> /// <remarks>채팅 윈도우에 이미 작성된 피어 메시지를 추적하는 딕셔너리</remarks> protected Dictionary<ShortGuid, ChatMessage> chatMessageDictionary = new Dictionary<ShortGuid, ChatMessage>(); #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 최대 릴레이 카운트 /// </summary> private int maximumRelayCount = 3; /// <summary> /// 메시지 발송 인덱스 /// </summary> /// <remarks>이 인스턴스에서 보낸 메시지 수를 추적하기 위해 사용하는 로컬 카운터</remarks> private long messageSendIndex = 0; /// <summary> /// 암호화 키 /// </summary> /// private string encryptionKey = "12345678901234567890123456789012345678"; // 암호화 키는 38자리를 설정해야 한다. #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 연결 타입 - ConnectionType /// <summary> /// 연결 타입 /// </summary> public ConnectionType ConnectionType { get; set; } #endregion #region 데이터 직렬화기 - DataSerializer /// <summary> /// 데이터 직렬화기 /// </summary> public DataSerializer DataSerializer { get; set; } #endregion #region 서버 IP 주소 - ServerIPAddress /// <summary> /// 서버 IP 주소 /// </summary> public string ServerIPAddress { get; set; } #endregion #region 서버 포트 - ServerPort /// <summary> /// 서버 포트 /// </summary> public int ServerPort { get; set; } #endregion #region 로컬명 - LocalName /// <summary> /// 로컬명 /// </summary> public string LocalName { get; set; } #endregion #region 로컬 서버 활성화 여부 - LocalServerEnabled /// <summary> /// 로컬 서버 활성화 여부 /// </summary> public bool LocalServerEnabled { get; set; } #endregion #region 암호화 활성화 여부 - EncryptionEnabled /// <summary> /// 암호화 활성화 여부 /// </summary> public bool EncryptionEnabled { get; set; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 첫번째 초기화 여부 - IsFirstInitialized /// <summary> /// 첫번째 초기화 여부 /// </summary> protected bool IsFirstInitialized { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ChatServerBase(localName, connectionType) /// <summary> /// 생성자 /// </summary> public ChatServerBase(string localName, ConnectionType connectionType) { LocalName = localName; ConnectionType = connectionType; ServerIPAddress = string.Empty; ServerPort = 10000; LocalServerEnabled = false; EncryptionEnabled = false; IsFirstInitialized = true; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 구성 갱신하기 - RefreshConfiguration() /// <summary> /// 구성 갱신하기 /// </summary> public void RefreshConfiguration() { if(IsFirstInitialized) { IsFirstInitialized = false; NetworkComms.AppendGlobalIncomingPacketHandler<ChatMessage>("ChatMessage", ProcessChatMessageReceived); NetworkComms.AppendGlobalConnectionCloseHandler(ProcessConnectionClosed); } NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions ( DataSerializer, NetworkComms.DefaultSendReceiveOptions.DataProcessors, NetworkComms.DefaultSendReceiveOptions.Options ); if ( EncryptionEnabled && !NetworkComms.DefaultSendReceiveOptions.DataProcessors.Contains(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>()) ) { RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, this.encryptionKey); NetworkComms.DefaultSendReceiveOptions.DataProcessors.Add(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>()); } else if ( !EncryptionEnabled && NetworkComms.DefaultSendReceiveOptions.DataProcessors.Contains(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>()) ) { NetworkComms.DefaultSendReceiveOptions.DataProcessors.Remove(DPSManager.GetDataProcessor<RijndaelPSKEncrypter>()); } if(LocalServerEnabled && ConnectionType == ConnectionType.TCP && !Connection.Listening(ConnectionType.TCP)) { #region 로컬 서버가 활성화 되고 연결 타입이 TCP이지만 TCP를 수신하지 않는 경우 처리한다. if(Connection.Listening(ConnectionType.UDP)) { AppendLineToChatHistory("연결 모드가 변경되었습니다. 기존 연결이 닫힙니다."); NetworkComms.Shutdown(); } else { AppendLineToChatHistory("로컬 서버 모드가 활성화 되었습니다. 기존 연결이 닫힙니다."); NetworkComms.Shutdown(); } Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, 0)); AppendLineToChatHistory("TCP 연결을 리스닝 합니다 :"); foreach(IPEndPoint listenEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP)) { AppendLineToChatHistory(listenEndPoint.Address + ":" + listenEndPoint.Port); } AppendLineToChatHistory(Environment.NewLine); #endregion } else if(LocalServerEnabled && ConnectionType == ConnectionType.UDP && !Connection.Listening(ConnectionType.UDP)) { #region 로컬 서버가 활성화 되고 연결 타입이 UDP이지만 UDP를 수신하지 않는 경우 처리한다. if(Connection.Listening(ConnectionType.TCP)) { AppendLineToChatHistory("연결 모드가 변경되었습니다. 기존 연결이 닫힙니다."); NetworkComms.Shutdown(); } else { AppendLineToChatHistory("로컬 서버 모드가 활성화 되었습니다. 기존 연결이 닫힙니다."); NetworkComms.Shutdown(); } Connection.StartListening(ConnectionType.UDP, new IPEndPoint(IPAddress.Any, 0)); AppendLineToChatHistory("UDP 연결을 리스닝 합니다 :"); foreach(IPEndPoint listenEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.UDP)) { AppendLineToChatHistory(listenEndPoint.Address + ":" + listenEndPoint.Port); } AppendLineToChatHistory(Environment.NewLine); #endregion } else if(!LocalServerEnabled && (Connection.Listening(ConnectionType.TCP) || Connection.Listening(ConnectionType.UDP))) { #region 로컬 서버가 비활성화 되고 TCP나 UDP를 수신하는 경우 처리한다. NetworkComms.Shutdown(); AppendLineToChatHistory("로컬 서버 모드가 비활성화 되었습니다. 기존 연결이 닫힙니다."); AppendLineToChatHistory(Environment.NewLine); #endregion } else if ( !LocalServerEnabled && ( ( ConnectionType == ConnectionType.UDP && NetworkComms.GetExistingConnection(ConnectionType.TCP).Count > 0 ) || ( ConnectionType == ConnectionType.TCP && NetworkComms.GetExistingConnection(ConnectionType.UDP).Count > 0 ) ) ) { #region 로컬 서버가 비활성화 되고 연결 타입이 UDP이고 TCP 연결이 있거나 연결 타입이 TCP이고 UDP 연결이 있는 경우 처리한다. NetworkComms.Shutdown(); AppendLineToChatHistory("연결 모드가 변경되었습니다. 기존 연결이 닫힙니다."); AppendLineToChatHistory(Environment.NewLine); #endregion } } #endregion #region 메시지 송신하기 - SendMessage(message) /// <summary> /// 메시지 송신하기 /// </summary> /// <param name="message">메시지</param> public void SendMessage(string message) { if(message.Trim() == string.Empty) { return; } ConnectionInfo serverConnectionInfo = null; if(ServerIPAddress != string.Empty) { try { serverConnectionInfo = new ConnectionInfo(ServerIPAddress, ServerPort); } catch(Exception) { ShowMessage("서버 IP 및 포트를 파싱하지 못했습니다. 내용이 올바른지 확인하고 다시 시도하십시오."); return; } } ChatMessage chatMessage = new ChatMessage ( NetworkComms.NetworkIdentifier, LocalName, message, this.messageSendIndex++ ); lock(this.chatMessageDictionary) { this.chatMessageDictionary[NetworkComms.NetworkIdentifier] = chatMessage; } AppendLineToChatHistory(chatMessage.SourceName + " - " + chatMessage.Message); ClearInputLine(); if(serverConnectionInfo != null) { try { if(ConnectionType == ConnectionType.TCP) { TCPConnection.GetConnection(serverConnectionInfo).SendObject("ChatMessage", chatMessage); } else if(ConnectionType == ConnectionType.UDP) { UDPConnection.GetConnection ( serverConnectionInfo, UDPOptions.None ).SendObject("ChatMessage", chatMessage); } else { throw new Exception("유효하지 않은 연결 타입이 설정되었습니다."); } } catch(CommsException) { AppendLineToChatHistory ( "에러 : 메시지 발송 중 통신 에러가 발생했습니다 : " + serverConnectionInfo + ". 설정을 확인하고 다시 시도하십시오." ); } catch(Exception) { AppendLineToChatHistory ( "에러 : 메시지 발송 중 일반 에러가 발생했습니다 : " + serverConnectionInfo + ". 설정을 확인하고 다시 시도하십시오." ); } } List<ConnectionInfo> otherConnectionInfoList; if(serverConnectionInfo != null) { otherConnectionInfoList = ( from current in NetworkComms.AllConnectionInfo() where current.RemoteEndPoint != serverConnectionInfo.RemoteEndPoint select current ).ToList(); } else { otherConnectionInfoList = NetworkComms.AllConnectionInfo(); } foreach(ConnectionInfo otherConnectionInfo in otherConnectionInfoList) { try { if(ConnectionType == ConnectionType.TCP) { TCPConnection.GetConnection(otherConnectionInfo).SendObject("ChatMessage", chatMessage); } else if(ConnectionType == ConnectionType.UDP) { UDPConnection.GetConnection ( otherConnectionInfo, UDPOptions.None ).SendObject("ChatMessage", chatMessage); } else { throw new Exception("유효하지 않은 연결 타입이 설정되었습니다."); } } catch(CommsException) { AppendLineToChatHistory ( "에러 : 메시지 발송 중 통신 에러가 발생했습니다 : " + otherConnectionInfo + ". 설정을 확인하고 다시 시도하십시오." ); } catch(Exception) { AppendLineToChatHistory ( "에러 : 메시지 발송 중 일반 에러가 발생했습니다 : " + otherConnectionInfo + ". 설정을 확인하고 다시 시도하십시오." ); } } return; } #endregion #region 채팅 히스토리에 라인 추가하기 - AppendLineToChatHistory(message) /// <summary> /// 채팅 히스토리에 라인 추가하기 /// </summary> /// <param name="message">메시지</param> public abstract void AppendLineToChatHistory(string message); #endregion #region 채팅 히스토리 지우기 - ClearChatHistory() /// <summary> /// 채팅 히스토리 지우기 /// </summary> public abstract void ClearChatHistory(); #endregion #region 입력 라인 지우기 - ClearInputLine() /// <summary> /// 입력 라인 지우기 /// </summary> public abstract void ClearInputLine(); #endregion #region 메시지 보여주기 - ShowMessage(message) /// <summary> /// 메시지 보여주기 /// </summary> /// <param name="message">메시지</param> public abstract void ShowMessage(string message); #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 채팅 메시지 수신시 처리하기 - ProcessChatMessageReceived(packetHeader, connection, chatMessage) /// <summary> /// 채팅 메시지 수신시 처리하기 /// </summary> /// <param name="packetHeader">패킷 헤더</param> /// <param name="connection">연결</param> /// <param name="chatMessage">채팅 메시지</param> protected virtual void ProcessChatMessageReceived(PacketHeader packetHeader, Connection connection, ChatMessage chatMessage) { lock(this.chatMessageDictionary) { if(this.chatMessageDictionary.ContainsKey(chatMessage.SourceIdentifier)) { if(this.chatMessageDictionary[chatMessage.SourceIdentifier].MessageIndex < chatMessage.MessageIndex) { AppendLineToChatHistory(chatMessage.SourceName + " - " + chatMessage.Message); this.chatMessageDictionary[chatMessage.SourceIdentifier] = chatMessage; } } else { this.chatMessageDictionary.Add(chatMessage.SourceIdentifier, chatMessage); AppendLineToChatHistory(chatMessage.SourceName + " - " + chatMessage.Message); } } if(chatMessage.RelayCount < this.maximumRelayCount) { Connection[] allRelayConnections = ( from current in NetworkComms.GetExistingConnection() where current != connection select current ).ToArray(); chatMessage.IncrementRelayCount(); foreach(Connection relayConnection in allRelayConnections) { try { relayConnection.SendObject("ChatMessage", chatMessage); } catch(CommsException) { } } } } #endregion #region 연결을 닫는 경우 처리하기 - ProcessConnectionClosed(connection) /// <summary> /// 연결을 닫는 경우 처리하기 /// </summary> /// <param name="connection">연결</param> private void ProcessConnectionClosed(Connection connection) { lock(this.chatMessageDictionary) { ShortGuid remoteSourceIdentifier = connection.ConnectionInfo.NetworkIdentifier; if(this.chatMessageDictionary.ContainsKey(remoteSourceIdentifier)) { AppendLineToChatHistory ( string.Format ( "'{0}' 연결이 닫혔습니다.", this.chatMessageDictionary[remoteSourceIdentifier].SourceName ) ); } else { AppendLineToChatHistory(string.Format("'{0} 연결이 닫혔습니다.", connection.ToString())); } this.chatMessageDictionary.Remove(connection.ConnectionInfo.NetworkIdentifier); } } #endregion #region 사용법 출력하기 - PrintUsageInstructions() /// <summary> /// 사용법 출력하기 /// </summary> public void PrintUsageInstructions() { AppendLineToChatHistory(""); AppendLineToChatHistory("채팅 사용 방법 :"); AppendLineToChatHistory(""); AppendLineToChatHistory("단계 1. 두 개 이상의 채팅 응용 프로그램을 엽니다."); AppendLineToChatHistory("단계 2. 단일 응용 프로그램에서 로컬 서버 모드를 활성화합니다 (설정 참조)."); AppendLineToChatHistory("단계 3. 나머지 응용 프로그램의 설정에 원격 서버 IP 및 포트 정보를 입력합니다."); AppendLineToChatHistory("단계 4. 채팅을 시작하십시오."); AppendLineToChatHistory(""); AppendLineToChatHistory("참고 : 연결은 첫 번째 메시지 전송시 설정됩니다."); AppendLineToChatHistory(""); } #endregion } } |
▶ ChatServer.cs
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 |
using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using NetworkCommsDotNet; using NetworkCommsDotNet.Connections; using NetworkCommsDotNet.DPSBase; using NetworkCommsDotNet.Tools; namespace TestProject { /// <summary> /// 채팅 서버 /// </summary> public class ChatServer : ChatServerBase { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 채팅 히스토리 텍스트 블럭 - ChatHistoryTextBlock /// <summary> /// 채팅 히스토리 텍스트 블럭 /// </summary> public TextBlock ChatHistoryTextBlock { get; private set; } #endregion #region 채팅 히스토리 스크롤러 뷰어 - ChatHistoryScrollerViewer /// <summary> /// 채팅 히스토리 스크롤러 뷰어 /// </summary> public ScrollViewer ChatHistoryScrollerViewer { get; private set; } #endregion #region 메시지 발송자 텍스트 박스 - MessagesSenderTextBox /// <summary> /// 메시지 발송자 텍스트 박스 /// </summary> public TextBox MessagesSenderTextBox { get; private set; } #endregion #region 메시지 텍스트 박스 - MessagesTextBox /// <summary> /// 메시지 텍스트 박스 /// </summary> public TextBox MessagesTextBox { get; private set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ChatServer(chatHistoryTextBlock, chatHistoryScrollViewer, messageSenderTextBox, messageTextBox) /// <summary> /// 생성자 /// </summary> /// <param name="chatHistoryTextBlock">채팅 히스토리 텍스트 박스</param> /// <param name="chatHistoryScrollViewer">채팅 히스토리 스크롤 뷰어</param> /// <param name="messageSenderTextBox">메시지 발송자 텍스트 박스</param> /// <param name="messageTextBox">메시지 텍스트 박스</param> public ChatServer ( TextBlock chatHistoryTextBlock, ScrollViewer chatHistoryScrollViewer, TextBox messageSenderTextBox, TextBox messageTextBox ) : base (HostInfo.HostName, ConnectionType.TCP) { this.ChatHistoryTextBlock = chatHistoryTextBlock; this.ChatHistoryScrollerViewer = chatHistoryScrollViewer; this.MessagesSenderTextBox = messageSenderTextBox; this.MessagesTextBox = messageTextBox; this.DataSerializer = DPSManager.GetDataSerializer<ProtobufSerializer>(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 채팅 히스토리 텍스트 블럭에 라인 추가하기 - AppendLineToChatHistoryTextBlock(fontStyle, text, addNewLine) /// <summary> /// 채팅 히스토리 텍스트 블럭에 라인 추가하기 /// </summary> /// <param name="fontStyle">폰트 스타일</param> /// <param name="text">텍스트</param> /// <param name="addNewLine">신규 라인 추가 여부</param> public void AppendLineToChatHistoryTextBlock(System.Drawing.FontStyle fontStyle, string text, bool addNewLine) { ChatHistoryTextBlock.Dispatcher.BeginInvoke ( new Action(() => { if(fontStyle == System.Drawing.FontStyle.Regular) { ChatHistoryTextBlock.Inlines.Add(new Run(text)); } else if(fontStyle == System.Drawing.FontStyle.Bold) { ChatHistoryTextBlock.Inlines.Add(new Bold(new Run(text))); } else if(fontStyle == System.Drawing.FontStyle.Italic) { ChatHistoryTextBlock.Inlines.Add(new Italic(new Run(text))); } else { ChatHistoryTextBlock.Inlines.Add ( new Run ( "에러 : 알 수 없는 글꼴 스타일을 가진 알 수 없는 텍스트를 추가하려고 했습니다." ) ); } if(addNewLine) { ChatHistoryTextBlock.Inlines.Add("\n"); } ChatHistoryScrollerViewer.ScrollToBottom(); }) ); } #endregion #region 메시지 발송자 텍스트 박스 갱신하기 - UpdateMessageSenderTextBox() /// <summary> /// 메시지 발송자 텍스트 박스 갱신하기 /// </summary> public void UpdateMessageSenderTextBox() { lock(this.chatMessageDictionary) { string[] sourceNameArray = ( from current in chatMessageDictionary.Values orderby current.SourceName select current.SourceName ).ToArray(); MessagesSenderTextBox.Dispatcher.BeginInvoke ( new Action<string[]>(userNameArray => { MessagesSenderTextBox.Text = string.Empty; foreach(string userName in userNameArray) { MessagesSenderTextBox.AppendText(userName + "\n"); } }), new object[] { sourceNameArray } ); } } #endregion #region 채팅 히스토리에 라인 추가하기 - AppendLineToChatHistory(message) /// <summary> /// 채팅 히스토리에 라인 추가하기 /// </summary> /// <param name="message">메시지</param> public override void AppendLineToChatHistory(string message) { AppendLineToChatHistoryTextBlock(System.Drawing.FontStyle.Regular, message, true); } #endregion #region 채팅 히스토리 지우기 - ClearChatHistory() /// <summary> /// 채팅 히스토리 지우기 /// </summary> public override void ClearChatHistory() { ChatHistoryTextBlock.Dispatcher.BeginInvoke ( new Action(() => { ChatHistoryTextBlock.Inlines.Clear(); ChatHistoryScrollerViewer.ScrollToBottom(); }) ); } #endregion #region 입력 라인 지우기 - ClearInputLine() /// <summary> /// 입력 라인 지우기 /// </summary> public override void ClearInputLine() { MessagesTextBox.Dispatcher.BeginInvoke ( new Action(() => { MessagesTextBox.Text = string.Empty; }) ); } #endregion #region 메시지 보여주기 - ShowMessage(message) /// <summary> /// 메시지 보여주기 /// </summary> /// <param name="message">메시지</param> public override void ShowMessage(string message) { MessageBox.Show(message); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 채팅 메시지 수신시 처리하기 - ProcessChatMessageReceived(packetHeader, connection, chatMessage) /// <summary> /// 채팅 메시지 수신시 처리하기 /// </summary> /// <param name="packetHeader">패킷 헤더</param> /// <param name="connection">연결</param> /// <param name="chatMessage">채팅 메시지</param> protected override void ProcessChatMessageReceived ( PacketHeader packetHeader, Connection connection, ChatMessage chatMessage ) { base.ProcessChatMessageReceived(packetHeader, connection, chatMessage); UpdateMessageSenderTextBox(); } #endregion } } |