public ClientSideViewModel(ILogger <ClientSideViewModel> logger)
 {
     this.Logger           = logger;
     this.BindingData      = new BindingDataModel();
     this.ClientSocket     = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     this.ReceivedMessages = new AsyncObservableCollection <string>(App.Current.Dispatcher);
     this.Handler          = new ClientThreadHandler(this);
 }
Example #2
0
        private async void RequestingClient_Acceptor()
        {
            client = default(TcpClient); //클라이언트 생성
            string name = null;

            byte[] message = null;
            await Task.Run(() =>
            {
                //내가 선택한 아이디에서 채팅방 들어오라고 질의는 어떻게 할까??

                while (true)
                {
                    client = server.AcceptTcpClient();
                    StatusBox.Invoke((MethodInvoker) delegate()
                    {
                        StatusBox.AppendText("Approve Client Access...\n");
                    });

                    NetworkStream stream = client.GetStream();

                    byte[] Stream_data = new byte[1024];
                    int Len            = stream.Read(Stream_data, 0, Stream_data.Length); //연결되면 클라이언트는 id+userlist를 보낸다.
                    string DataFormat  = Encoding.Default.GetString(Stream_data, 0, Len); //string형식으로 인코딩합니다.
                    name = DataFormat.Split('+')[0];
                    string UsersString = DataFormat.Split('+')[1];
                    stream.Flush();
                    message = Encoding.Default.GetBytes(Packet.Approve);
                    stream.Write(message, 0, message.Length);
                    stream.Flush();

                    List_of_client.Add(client, name);                                                     //클라이언트 객체와 id저장

                    ChatClientAction Branch_client     = new ChatClientAction(client, name, UsersString); //UserString : user1,user2,user3...
                    Branch_client.Receive_Action      += new ChatClientAction.MessageReceive_Throw(Received_Message);
                    Branch_client.Shutdown_Action     += new ChatClientAction.ShutdownCode_Throw(ExitServer);
                    ClientThreadHandler RunningMachine = new ClientThreadHandler(Branch_client.Start_Thread_of_Client);
                    BeginInvoke(RunningMachine);
                }
            });
        }
Example #3
0
        private async void RequestingClient_Acceptor()
        {
            client = default(TcpClient); //클라이언트 생성
            string name = null;          //해당 연결된 클라이언트의 id를 저장

            byte[] message = null;       //패킷을 담을 공간
            await Task.Run(() =>         //비동기적 실행(await)
            {
                while (true)
                {
                    client = server.AcceptTcpClient();
                    statusBox.Invoke((MethodInvoker) delegate()
                    {
                        statusBox.AppendText("Approve Client Access...\n");
                    });

                    NetworkStream stream = client.GetStream();                 //해당 클라이언트와 네트워크 스트림 생성
                    byte[] Stream_data   = new byte[1024];
                    int Len = stream.Read(Stream_data, 0, Stream_data.Length); //연결되면 클라이언트는 id를 보낸다.
                    name    = Encoding.Default.GetString(Stream_data, 0, Len); //string형식으로 인코딩합니다.
                    stream.Flush();

                    message = Encoding.Default.GetBytes(Packet.Approve); //연결 허가 패킷제작
                    stream.Write(message, 0, message.Length);            //위 패킷 전송
                    stream.Flush();

                    List_of_client.Add(client, name);                                                                 //클라이언트 객체와 id저장

                    HomeClientAction Branch_client     = new HomeClientAction(client, name);                          //서버사이드 쓰레드의 생성
                    Branch_client.Receive_Action      += new HomeClientAction.MessageReceive_Throw(Received_Message); //이벤트 함수추가1
                    Branch_client.Shutdown_Action     += new HomeClientAction.ShutdownCode_Throw(ExitServer);         //이벤트 함수추가2
                    ClientThreadHandler RunningMachine = new ClientThreadHandler(Branch_client.Start_Thread_of_Client);
                    BeginInvoke(RunningMachine);
                    statusBox.Invoke((MethodInvoker) delegate()
                    {
                        statusBox.AppendText($"{name} Login...\n");
                    });

                    try
                    {
                        connection.Open();
                        connection2.Open();
                        command.CommandText = "update userlist set status='green' where ID='" + name + "'"; //userlist의 해당 아이디상태 그린으로 업데이트
                        command.ExecuteNonQuery();                                                          //위 쿼리문 실행
                        command.CommandText = "select ID from userlist";                                    //그리고 유저리스트의 id모두 찾아서
                        reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            command2.CommandText = "update " + reader["ID"].ToString() + "_friends set status='green' where ID='" + name + "'"; //그 아이디의 친구목록에서 해당 아이디상태 변경
                            command2.ExecuteNonQuery();
                        }
                        Task.Run(() => {
                            foreach (var User in List_of_client)
                            {
                                TcpClient client    = User.Key;
                                stream              = client.GetStream();
                                byte[] Stream_data_ = Encoding.Default.GetBytes(Packet.ChangeSignal); //테이블의 상태변화 되었음을 알림

                                stream.Write(Stream_data_, 0, Stream_data_.Length);
                                stream.Flush();
                            }
                        });
                    }
                    catch (Exception err) { }
                    finally
                    {
                        reader.Close();
                        connection.Close();
                        connection2.Close();
                    }
                }
            });
        }