async void recieveMessage(NetworkStream stream) { try { while (true) { msg = ChattingMessageUtil.Recieve(stream); if (msg == null) { continue; } if (msg.header.MSGTYPE == CONSTANT.FLOODING) { string chat = Encoding.Default.GetString(msg.body.GetBytes()); appendText(tbxChattingLog, chat); } else if (msg.header.MSGTYPE == CONSTANT.NOTICE) { string notice = Encoding.Default.GetString(msg.body.GetBytes()); appendText(tbxChattingLog, notice); } } } catch (SocketException) { stream.Close(); client.Close(); } catch (IOException) { stream.Close(); client.Close(); } }
private void btnConnect_Click(object sender, EventArgs e) { if (client != default(TcpClient)) { return; } string serverIP = tbxServerIP.Text; int serverPort = int.Parse(tbxServerPort.Text); clientAddress = new IPEndPoint(IPAddress.Loopback, 0); serverAddress = new IPEndPoint(IPAddress.Parse(serverIP), serverPort); client = new TcpClient(clientAddress); if (!connectToServer(3)) { return; //서버와의 연결 성공 여부에 따라 } stream = client.GetStream(); //채팅 서버 접속자들에게 자신의 접속을 알리기 위한 메세지를 서버에 보냄 ChattingMessage.Message msg = makeConnectionMessage(Nickname); sendMessage(stream, msg); recieveTask = Task.Run(() => recieveMessage(stream)); }
private void btnEnter_Click(object sender, EventArgs e) { if (stream == default(NetworkStream)) { return; } if (tbxInput.Text == null || tbxInput.Text.Length == 0) { return; } ChattingMessage.Message msg = makeChattingMessage(tbxInput.Text); tbxInput.Clear(); sendMessage(stream, msg); }
void sendMessage(NetworkStream stream, ChattingMessage.Message msg) { try { ChattingMessageUtil.Send(stream, msg); } catch (SocketException) { stream.Close(); client.Close(); Application.Exit(); } catch (IOException) { stream.Close(); client.Close(); Application.Exit(); } catch (ObjectDisposedException) { appendText(tbxChattingLog, "[전송 실패: 서버와의 연결 종료됨]"); } }
private void btnChangeName_Click(object sender, EventArgs e) { if (stream == default(NetworkStream)) { return; } if (tbxNickname.Text == null || tbxNickname.Text.Length == 0) { appendText(tbxChattingLog, "유효하지 않은 닉네임입니다."); return; } string oldNickname = Nickname; Nickname = tbxNickname.Text; ChattingMessage.Message msg = makeChangeNicknameMessage(oldNickname, Nickname); sendMessage(stream, msg); }