コード例 #1
0
        private void Listener(IPAddress localaddr, int port)
        {
            TcpListener listener = null;

            try
            {
                listener = new TcpListener(localaddr, port);
                listener.Start();
                Active(true);
                while (active)
                {
                    if (listener.Pending())
                    {
                        try
                        {
                            MyClient obj = new MyClient();
                            obj.id     = id;
                            obj.client = listener.AcceptTcpClient();
                            obj.stream = obj.client.GetStream();
                            obj.buffer = new byte[obj.client.ReceiveBufferSize];
                            obj.data   = new StringBuilder();
                            obj.handle = new EventWaitHandle(false, EventResetMode.AutoReset);
                            Thread th = new Thread(() => Connection(obj))
                            {
                                IsBackground = true
                            };
                            th.Start();
                            id++;
                        }
                        catch (Exception ex)
                        {
                            LogWrite(string.Format("[/ {0} /]", ex.Message));
                        }
                    }
                    else
                    {
                        Thread.Sleep(500);
                    }
                }
                Active(false);
            }
            catch (Exception ex)
            {
                LogWrite(string.Format("[/ {0} /]", ex.Message));
            }
            finally
            {
                if (listener != null)
                {
                    listener.Server.Close();
                }
            }
        }
コード例 #2
0
        private void Listener(IPAddress ip, int port)
        {
            TcpListener listener = null;

            try
            {
                listener = new TcpListener(ip, port);
                listener.Start();
                Active(true);
                while (_active)
                {
                    if (listener.Pending())
                    {
                        try
                        {
                            MyClient obj = new MyClient
                            {
                                Id = _id, Username = new StringBuilder(), Client = listener.AcceptTcpClient()
                            };
                            obj.Stream = obj.Client.GetStream();
                            obj.Buffer = new byte[obj.Client.ReceiveBufferSize];
                            obj.Data   = new StringBuilder();
                            obj.Handle = new EventWaitHandle(false, EventResetMode.AutoReset);
                            Thread th = new Thread(() => Connection(obj))
                            {
                                IsBackground = true
                            };
                            th.Start();
                            _id++;
                        }
                        catch (Exception ex)
                        {
                            Log(ErrorMsg(ex.Message));
                        }
                    }
                    else
                    {
                        Thread.Sleep(500);
                    }
                }
                Active(false);
            }
            catch (Exception ex)
            {
                Log(ErrorMsg(ex.Message));
            }
            finally
            {
                listener?.Server.Close();
            }
        }
コード例 #3
0
ファイル: Server.cs プロジェクト: 5l1v3r1/chat-app
        private void Write(IAsyncResult result)
        {
            MyClient obj = (MyClient)result.AsyncState;

            if (obj.client.Connected)
            {
                try
                {
                    obj.stream.EndWrite(result);
                }
                catch (IOException e) { LogWrite(string.Format("[/ {0} /]", e.Message)); }
                catch (ObjectDisposedException e) { LogWrite(string.Format("[/ {0} /]", e.Message)); }
            }
        }
コード例 #4
0
 private void BeginWrite(string msg, MyClient obj) // send the message to a specific client
 {
     byte[] buffer = Encoding.UTF8.GetBytes(msg);
     if (obj.Client.Connected)
     {
         try
         {
             obj.Stream.BeginWrite(buffer, 0, buffer.Length, Write, obj);
         }
         catch (Exception ex)
         {
             Log(ErrorMsg(ex.Message));
         }
     }
 }
コード例 #5
0
ファイル: Server.cs プロジェクト: suresh-kr-git/chat-app
        private void Write(IAsyncResult result)
        {
            MyClient obj = (MyClient)result.AsyncState;

            if (obj.client.Connected)
            {
                try
                {
                    obj.stream.EndWrite(result);
                }
                catch (Exception ex)
                {
                    Log(string.Format("ERROR: {0}", ex.Message));
                }
            }
        }
コード例 #6
0
        private void Write(IAsyncResult result)
        {
            MyClient obj = (MyClient)result.AsyncState;

            if (obj.Client.Connected)
            {
                try
                {
                    obj.Stream.EndWrite(result);
                }
                catch (Exception ex)
                {
                    Log(ErrorMsg(ex.Message));
                }
            }
        }
コード例 #7
0
ファイル: Server.cs プロジェクト: suresh-kr-git/chat-app
        private void Read(IAsyncResult result)
        {
            MyClient obj   = (MyClient)result.AsyncState;
            int      bytes = 0;

            if (obj.client.Connected)
            {
                try
                {
                    bytes = obj.stream.EndRead(result);
                }
                catch (Exception ex)
                {
                    Log(string.Format("ERROR: {0}", ex.Message));
                }
            }
            if (bytes > 0)
            {
                obj.data.AppendFormat("{0}", Encoding.UTF8.GetString(obj.buffer, 0, bytes));
                try
                {
                    if (obj.stream.DataAvailable)
                    {
                        obj.stream.BeginRead(obj.buffer, 0, obj.buffer.Length, new AsyncCallback(Read), obj);
                    }
                    else
                    {
                        string msg = string.Format("{0}: {1}", obj.name, obj.data);
                        Log(msg);
                        Send(msg, obj.id);
                        obj.data.Clear();
                        obj.handle.Set();
                    }
                }
                catch (Exception ex)
                {
                    obj.data.Clear();
                    Log(string.Format("ERROR: {0}", ex.Message));
                    obj.handle.Set();
                }
            }
            else
            {
                obj.client.Close();
                obj.handle.Set();
            }
        }
コード例 #8
0
        private void Read(IAsyncResult result)
        {
            MyClient obj   = (MyClient)result.AsyncState;
            int      bytes = 0;

            if (obj.Client.Connected)
            {
                try
                {
                    bytes = obj.Stream.EndRead(result);
                }
                catch (Exception ex)
                {
                    Log(ErrorMsg(ex.Message));
                }
            }
            if (bytes > 0)
            {
                obj.Data.AppendFormat("{0}", Encoding.UTF8.GetString(obj.Buffer, 0, bytes));
                try
                {
                    if (obj.Stream.DataAvailable)
                    {
                        obj.Stream.BeginRead(obj.Buffer, 0, obj.Buffer.Length, Read, obj);
                    }
                    else
                    {
                        string msg = $"{obj.Username}: {obj.Data}";
                        Log(msg);
                        Send(msg, obj.Id);
                        obj.Data.Clear();
                        obj.Handle.Set();
                    }
                }
                catch (Exception ex)
                {
                    obj.Data.Clear();
                    Log(ErrorMsg(ex.Message));
                    obj.Handle.Set();
                }
            }
            else
            {
                obj.Client.Close();
                obj.Handle.Set();
            }
        }
コード例 #9
0
        private bool Authorize(MyClient obj)
        {
            bool success = false;

            while (obj.Client.Connected)
            {
                try
                {
                    obj.Stream.BeginRead(obj.Buffer, 0, obj.Buffer.Length, ReadAuth, obj);
                    obj.Handle.WaitOne();
                    if (obj.Username.Length > 0)
                    {
                        success = true;
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Log(ErrorMsg(ex.Message));
                }
            }
            return(success);
        }
コード例 #10
0
        private bool Authorize(MyClient obj)
        {
            bool success = false;

            while (obj.client.Connected)
            {
                try
                {
                    obj.stream.BeginRead(obj.buffer, 0, obj.buffer.Length, new AsyncCallback(ReadAuth), obj);
                    obj.handle.WaitOne();
                    if (obj.username.Length > 0)
                    {
                        success = true;
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Log(ErrorMsg(ex.Message));
                }
            }
            return(success);
        }
コード例 #11
0
        private void Connection(MyClient obj)
        {
            list.TryAdd(obj.id, obj);
            OnConnected(obj);
            if (obj.stream.CanRead && obj.stream.CanWrite)
            {
                while (obj.client.Connected)
                {
                    try
                    {
                        obj.stream.BeginRead(obj.buffer, 0, obj.buffer.Length, new AsyncCallback(Read), obj);
                        obj.handle.WaitOne();
                    }
                    catch (IOException e)
                    {
                        //LogWrite(string.Format("[/ {0} /]", e.Message));
                        ErrorEvent(obj, e.Message);
                    }
                    catch (ObjectDisposedException e)
                    {
                        //LogWrite(string.Format("[/ {0} /]", e.Message));
                        ErrorEvent(obj, e.Message);
                    }
                }
            }
            else
            {
                //LogWrite(string.Format("[/ Client {0} stream cannot read/write /]", obj.id));
                ErrorEvent(obj, "Client {0} stream cannot read/write");
            }

            obj.client.Close();
            list.TryRemove(obj.id, out MyClient tmp);
            OnDisconnected(obj);

            //LogWrite(string.Format("[/ Client {0} connection closed /]", obj.id));
        }
コード例 #12
0
        private void Receive()
        {
            int threadIdx = connecCount;

            try
            {
                string strMsg;

                TcpClient client = sockServer.AcceptTcpClient();//Accept

                NetworkStream ns = client.GetStream();
                StreamReader  sr = new StreamReader(ns);
                StreamWriter  sw = new StreamWriter(ns);

                receiveThreadList.Add(new Thread(Receive));
                receiveThreadList[++connecCount].Start();

                while (true)
                {
                    try
                    {
                        strMsg = sr.ReadLine();
                        if (strMsg == null)
                        {
                            continue;
                        }
                        if (strMsg.Split(':')[0] == ((int)ProtocolNames.SetClient).ToString())
                        {
                            sw.WriteLine(((int)ProtocolNames.Connect).ToString() + ':' + (connecCount - 1));
                            sw.Flush();

                            Console.WriteLine("UserId : " + strMsg.Split(':')[1] + " Idx : " + (connecCount - 1) + " PC Connect");
                            MyClient currentClient = new MyClient();;
                            currentClient.Init(client, ns, sr, sw, strMsg.Split(':')[1], connecCount - 1);
                            clientList.Add(currentClient);
                        }
                        else if (strMsg.Split(':')[0] == ((int)ProtocolNames.ConnectUnityServer).ToString())
                        {
                            unityServer = new MyClient();;
                            unityServer.Init(client, ns, sr, sw);
                            Console.WriteLine("Unity Server Connect");
                        }
                        else if (strMsg.Split(':')[0] == ((int)ProtocolNames.GetClientStateRequest).ToString())
                        {
                            string indexData = "";
                            int    count     = 0;
                            foreach (MyClient item in clientList)
                            {
                                if (!item.client.Connected)
                                {
                                    continue;
                                }
                                count++;
                                indexData += item.id + ">" + item.idx;
                                if (count == 1)
                                {
                                    indexData += ',';
                                }
                            }
                            if (count == 1)
                            {
                                if (indexData[0] == '1')
                                {
                                    indexData += "0>" + -1;
                                }
                                else
                                {
                                    indexData += "1>" + -1;
                                }
                            }
                            else if (count == 0)
                            {
                                indexData = "0>-1,1>-1";
                            }
                            unityServer.sw.WriteLine(((int)ProtocolNames.GetClientStateResponse).ToString() + ':' + indexData);
                            unityServer.sw.Flush();
                        }
                        else if (strMsg.Split(':')[0] == ((int)ProtocolNames.RunClientUnityRequest).ToString())
                        {
                            foreach (MyClient item in clientList)
                            {
                                if (!item.client.Connected)
                                {
                                    continue;
                                }
                                if (item.idx == int.Parse(strMsg.Split(':')[1].Split(',')[0]) || item.idx == int.Parse(strMsg.Split(':')[1].Split(',')[1]))
                                {
                                    item.sw.WriteLine(((int)ProtocolNames.RunClientUnityResponse).ToString());
                                    item.sw.Flush();
                                }
                            }
                        }
                        else if (strMsg.Split(':')[0] == ((int)ProtocolNames.CloseUnityRequest).ToString())
                        {
                            foreach (MyClient item in clientList)
                            {
                                if (!item.client.Connected)
                                {
                                    continue;
                                }
                                if (item.idx == int.Parse(strMsg.Split(':')[1].Split(',')[0]) || item.idx == int.Parse(strMsg.Split(':')[1].Split(',')[1]))
                                {
                                    item.sw.WriteLine(((int)ProtocolNames.CloseUnityResponse).ToString());
                                    item.sw.Flush();
                                }
                            }
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Disconnect");
                        sw.Close();
                        sr.Close();
                        ns.Close();
                        client.Close();
                        receiveThreadList[threadIdx].Abort();
                    }
                }

                sockServer.Stop();

                Console.WriteLine("Client 연결 종료!");
            }
            catch (SocketException e)
            {
                Console.WriteLine(e.ToString());
            }
        }
コード例 #13
0
ファイル: Server.cs プロジェクト: 5l1v3r1/chat-app
        private void Read(IAsyncResult result)
        {
            MyClient obj   = (MyClient)result.AsyncState;
            int      bytes = 0;

            if (obj.client.Connected)
            {
                try
                {
                    bytes = obj.stream.EndRead(result);
                }
                catch (IOException e) { LogWrite(string.Format("[/ {0} /]", e.Message)); }
                catch (ObjectDisposedException e) { LogWrite(string.Format("[/ {0} /]", e.Message)); }
            }
            if (bytes > 0)
            {
                obj.data.AppendFormat("{0}", Encoding.UTF8.GetString(obj.buffer, 0, bytes));
                bool dataAvailable = false;
                try
                {
                    dataAvailable = obj.stream.DataAvailable;
                }
                catch (IOException e) { LogWrite(string.Format("[/ {0} /]", e.Message)); }
                catch (ObjectDisposedException e) { LogWrite(string.Format("[/ {0} /]", e.Message)); }
                if (dataAvailable)
                {
                    try
                    {
                        obj.stream.BeginRead(obj.buffer, 0, obj.buffer.Length, new AsyncCallback(Read), obj);
                    }
                    catch (IOException e)
                    {
                        LogWrite(string.Format("[/ {0} /]", e.Message));
                        obj.handle.Set();
                    }
                    catch (ObjectDisposedException e)
                    {
                        LogWrite(string.Format("[/ {0} /]", e.Message));
                        obj.handle.Set();
                    }
                }
                else
                {
                    string msg = string.Format("<- Client {0} -> " + obj.data, obj.id);
                    LogWrite(msg);
                    if (send == null || send.IsCompleted)
                    {
                        send = Task.Factory.StartNew(() => Send(msg, obj.id));
                    }
                    else
                    {
                        send.ContinueWith(antecendent => Send(msg, obj.id));
                    }
                    obj.data.Clear();
                    obj.handle.Set();
                }
            }
            else
            {
                obj.client.Close();
                obj.handle.Set();
            }
        }
コード例 #14
0
        private void Read(IAsyncResult result)
        {
            MyClient obj   = (MyClient)result.AsyncState;
            int      bytes = 0;

            if (obj.client.Connected)
            {
                try
                {
                    bytes = obj.stream.EndRead(result);
                }
                catch (IOException e) { LogWrite(String.Format("[/ {0} /]", e.Message)); }
                catch (ObjectDisposedException e) { LogWrite(String.Format("[/ {0} /]", e.Message)); }
            }
            if (bytes > 0)
            {
                // obj.data.AppendFormat("{0}", Encoding.UTF8.GetString(obj.buffer, 0, bytes));
                bool dataAvailable = false;
                try
                {
                    dataAvailable = obj.stream.DataAvailable;
                }
                catch (IOException e) { LogWrite(String.Format("[/ {0} /]", e.Message)); }
                catch (ObjectDisposedException e) { LogWrite(String.Format("[/ {0} /]", e.Message)); }
                if (dataAvailable)
                {
                    try
                    {
                        obj.stream.BeginRead(obj.buffer, 0, obj.buffer.Length, new AsyncCallback(Read), obj);
                    }
                    catch (IOException e)
                    {
                        LogWrite(String.Format("[/ {0} /]", e.Message));
                        obj.handle.Set();
                    }
                    catch (ObjectDisposedException e)
                    {
                        LogWrite(String.Format("[/ {0} /]", e.Message));
                        obj.handle.Set();
                    }
                }
                else
                {
                    IFormatter      formatter = new BinaryFormatter();
                    MemoryStream    ms        = new MemoryStream(obj.buffer);
                    chatLib.Message msg       = (chatLib.Message)formatter.Deserialize(ms);

                    switch (msg.Head)
                    {
                    case chatLib.Message.Header.POST:
                        LogWrite(String.Format("{0} -> {1} ", msg.MessageList[0], msg.MessageList[1]));
                        break;

                    case chatLib.Message.Header.FILE:
                        LogWrite(String.Format("{0} -> {1} Adında Dosya Gönderdi ", msg.MessageList[0], msg.MessageList[1]));
                        break;

                    case chatLib.Message.Header.REGISTER:
                        LogWrite(String.Format("{0} -> Kayıt Oldu ", msg.MessageList[0]));
                        break;

                    case chatLib.Message.Header.JOIN:
                        LogWrite(String.Format("{0} -> Giriş Yaptı ", msg.MessageList[0]));

                        break;
                    }


                    //String msg = String.Format("<- Client {0} -> " + obj.data, obj.id);
                    //LogWrite(msg);
                    if (send == null || send.IsCompleted)
                    {
                        switch (msg.Head)
                        {
                        case chatLib.Message.Header.REGISTER:
                            chatLib.Message message = new chatLib.Message(chatLib.Message.Header.REGISTER);
                            if (users.ContainsKey(msg.MessageList[0]))
                            {
                                message.addData("error");
                            }
                            else
                            {
                                users.Add(msg.MessageList[0], MD5Sifrele(msg.MessageList[1]));
                                message.addData("success");

                                string text = "";
                                foreach (DictionaryEntry item in users)
                                {
                                    text += item.Key.ToString() + "|" + item.Value.ToString() + ";";
                                }

                                text = text.Trim(';');

                                File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "users.txt", text);
                            }

                            send = Task.Factory.StartNew(() => SendOne(message, obj.id));
                            break;

                        case chatLib.Message.Header.JOIN:
                            chatLib.Message message1 = new chatLib.Message(chatLib.Message.Header.JOIN);
                            if (users.ContainsKey(msg.MessageList[0]))
                            {
                                if (users[msg.MessageList[0]].Equals(MD5Sifrele(msg.MessageList[1])))
                                {
                                    message1.addData("success");
                                    message1.addData(msg.MessageList[0]);
                                }
                                message1.addData("error");
                            }
                            else
                            {
                                message1.addData("error");
                            }

                            send = Task.Factory.StartNew(() => SendOne(message1, obj.id));
                            break;

                        case chatLib.Message.Header.POST:
                            send = Task.Factory.StartNew(() => Send(msg, obj.id));
                            break;

                        case chatLib.Message.Header.FILE:
                            send = Task.Factory.StartNew(() => Send(msg, obj.id));
                            break;
                        }
                    }
                    else
                    {
                        switch (msg.Head)
                        {
                        case chatLib.Message.Header.REGISTER:
                            chatLib.Message message = new chatLib.Message(chatLib.Message.Header.REGISTER);
                            if (users.ContainsKey(msg.MessageList[0]))
                            {
                                message.addData("error");
                            }
                            else
                            {
                                users.Add(msg.MessageList[0], MD5Sifrele(msg.MessageList[1]));
                                message.addData("success");

                                string text = "";
                                foreach (DictionaryEntry item in users)
                                {
                                    text += item.Key.ToString() + "|" + item.Value.ToString() + ";";
                                }

                                text = text.Trim(';');

                                File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "users.txt", text);
                            }
                            send.ContinueWith(antecendent => SendOne(message, obj.id));
                            break;

                        case chatLib.Message.Header.JOIN:
                            chatLib.Message message1 = new chatLib.Message(chatLib.Message.Header.JOIN);
                            if (users.ContainsKey(msg.MessageList[0]))
                            {
                                if (users[msg.MessageList[0]].Equals(MD5Sifrele(msg.MessageList[1])))
                                {
                                    message1.addData("success");
                                    message1.addData(msg.MessageList[0]);
                                }
                                message1.addData("error");
                            }
                            else
                            {
                                message1.addData("error");
                            }

                            send.ContinueWith(antecendent => SendOne(message1, obj.id));
                            break;

                        case chatLib.Message.Header.POST:
                            send.ContinueWith(antecendent => Send(msg, obj.id));
                            break;

                        case chatLib.Message.Header.FILE:
                            send.ContinueWith(antecendent => Send(msg, obj.id));
                            break;
                        }
                    }
                    //obj.data.Clear();
                    obj.handle.Set();
                }
            }
            else
            {
                obj.client.Close();
                obj.handle.Set();
            }
        }