Beispiel #1
0
        public bool SendString(String str)
        {
            bool result = false;

            try
            {
                if (client != null && client.Connected)
                {
                    // 메시지 보내기
                    byte[] msg = System.Text.Encoding.UTF8.GetBytes(str);
                    nStream.Write(msg, 0, msg.Length);
                    nStream.Flush();

                    SocketSendEventArgs sev = new SocketSendEventArgs(this.id, msg.Length);
                    Sent(sev);

                    result = true;
                }
            }
            catch (Exception err)
            {
                SocketErrorEventArgs eev = new SocketErrorEventArgs(this.id, err);
                ErrorOccured(eev);
            }
            return(result);
        }
Beispiel #2
0
        /// <summary>
        /// 서버에 연결된 모든 Client에게 데이터를 송신 한다.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="data_length"></param>
        /// <returns></returns>
        public bool BroadCast(byte[] data, int data_length)
        {
            bool result = false;

            try
            {
                foreach (var client in RemoteClients.ToList())
                {
                    if (client.Value != null)
                    {
                        NetworkStream stream = client.Value.GetStream();
                        if (stream != null)
                        {
                            stream.Write(data, 0, data_length);
                            stream.Flush();
                            result = true;
                        }
                    }
                    SocketSendEventArgs sev = new SocketSendEventArgs(this.id, data_length);
                    Sent(sev);
                }
            }
            catch (Exception err)
            {
                SocketErrorEventArgs eev = new SocketErrorEventArgs(this.id, err);
                ErrorOccured(eev);
                //Debug.WriteLine("ServerSocket->BroadCast Error:"+err.Message);
            }
            return(result);
        }
Beispiel #3
0
        protected virtual void ErrorOccured(SocketErrorEventArgs e)
        {
            SocketErrorEventHandler handler = OnError;

            if (handler != null)
            {
                handler(this, e);
            }
        }
Beispiel #4
0
        /// <summary>
        /// 서버 접속 대기 상태 처리
        /// </summary>
        private void AcceptThread()
        {
            try
            {
                serverListener = new TcpListener(IPAddress.Parse(IP), Port);
                serverListener.Start();
                updateStatusInfo(string.Format("{0}:{1} server start:{2}", IP, Port, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")));

                while (ThreadRun)
                {
                    TcpClient client = serverListener.AcceptTcpClient();
                    //string remoteip = client.Client.RemoteEndPoint.ToString().Split(':')[0];
                    string remoteip = client.Client.RemoteEndPoint.ToString();
                    RemoteClients.Add(remoteip, client);

                    Thread clientworker = new Thread(new ParameterizedThreadStart(clientThread));
                    clientworker.IsBackground = true;
                    clientworker.Start(client);

                    // Client를 Accept 했다고 Event를 발생시킨다.
                    SocketAcceptEventArgs aev = new SocketAcceptEventArgs(client);
                    Accepted(aev);
                }
            }
            catch (SocketException se)
            {
                SocketErrorEventArgs eev = new SocketErrorEventArgs(this.id, se);
                ErrorOccured(eev);
            }
            catch (Exception ex)
            {
                SocketErrorEventArgs eev = new SocketErrorEventArgs(this.id, ex);
                ErrorOccured(eev);
            }
            finally
            {
                if (serverListener != null)
                {
                    serverListener.Stop();
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// 서버 를 동작 시킨다.
        /// </summary>
        /// <param name="ip">서버 동작 IP</param>
        /// <param name="port">서버 동작 Port</param>
        /// <returns>false:서버 Open 실패, true:서버 Open 성공</returns>
        public bool StartServer(string ip, int port)
        {
            bool result = false;

            try
            {
                this.IP      = ip;
                this.Port    = port;
                ThreadRun    = true;
                serverThread = new Thread(new ThreadStart(AcceptThread));
                serverThread.IsBackground = true;
                serverThread.Start();
                result = true;
            }
            catch (Exception err)
            {
                SocketErrorEventArgs eev = new SocketErrorEventArgs(this.id, err);
                ErrorOccured(eev);
            }
            return(result);
        }
Beispiel #6
0
        private void ClientThread(object sender)
        {
            TcpClient   client = sender as TcpClient;
            StateObject so     = new StateObject(client);
            int         i;

            try
            {
                while (ThreadRun && (i = nStream.Read(so.Buffer, 0, so.BufferSize)) != 0)
                {
                    SocketReceiveEventArgs rev = new SocketReceiveEventArgs(id, i, so.Buffer);
                    Received(rev);

//                    string data = System.Text.Encoding.UTF8.GetString(so.Buffer, 0, i);
//                    Debug.WriteLine("Client Read:" + data);
                }
            }
            catch (SocketException se)
            {
                SocketErrorEventArgs eev = new SocketErrorEventArgs(this.id, se);
                ErrorOccured(eev);
            }
            catch (Exception err)
            {
                SocketErrorEventArgs eev = new SocketErrorEventArgs(this.id, err);
                ErrorOccured(eev);
            }
            finally
            {
                if (nStream != null)
                {
                    nStream.Close();
                    nStream = null;
                }
                if (client != null)
                {
                    client.Close();
                }
            }
        }
Beispiel #7
0
        public bool Connect(string Ip, int port)
        {
            bool result = false;

            try
            {
                client = new TcpClient(Ip, port);
                if (client != null && client.Connected)
                {
                    ThreadRun = true;
                    nStream   = client.GetStream();
                    //                rStream = new StreamReader(nStream, Encoding.UTF8);     // Get Message
                    //                wStream = new StreamWriter(nStream, Encoding.UTF8);     // Get Message

                    Thread c_thread = new Thread(new ParameterizedThreadStart(ClientThread));
                    if (c_thread != null)
                    {
                        c_thread.Start(client);
                        // 연결 성공 이벤트를 날린다.
                        SocketConnectionEventArgs cev = new SocketConnectionEventArgs(this.id);
                        Connected(cev);
                        result = true;
                    }
                }
            }
            catch (SocketException se)
            {
                SocketErrorEventArgs eev = new SocketErrorEventArgs(this.id, se);
                ErrorOccured(eev);
            }
            catch (Exception err)
            {
                SocketErrorEventArgs eev = new SocketErrorEventArgs(this.id, err);
                ErrorOccured(eev);
            }

            return(result);
        }
Beispiel #8
0
        public bool Send(byte[] data, int data_size)
        {
            bool result = false;

            try
            {
                if (nStream != null && client.Connected)
                {
                    nStream.Write(data, 0, data_size);
                    nStream.Flush();

                    SocketSendEventArgs sev = new SocketSendEventArgs(this.id, data_size);
                    Sent(sev);

                    result = true;
                }
            }
            catch (Exception err)
            {
                SocketErrorEventArgs eev = new SocketErrorEventArgs(this.id, err);
                ErrorOccured(eev);
            }
            return(result);
        }
Beispiel #9
0
 private void OnClientError(object sender, SocketErrorEventArgs e)
 {
     AddLog(Log.Type.LOG_ERR, "HOST -> PC: Error ID: " + e.ID.ToString() + " Error Message: " + e.SocketException.ToString());
 }
Beispiel #10
0
        /// <summary>
        /// 외부 접속 처리 쓰레드
        /// </summary>
        /// <param name="sender"></param>
        private void clientThread(object sender)
        {
            /*
             *          string Name = string.Empty;
             *          string Subject = string.Empty;
             *          Int32 Grade = 0;
             *          string Memo = string.Empty;
             *          TimeSpan time = TimeSpan.Zero;
             */
            // 1. 데이타 받기
            TcpClient     client = sender as TcpClient;
            NetworkStream stream = client.GetStream();

            //            byte[] buffer = new byte[8092];
            StateObject so = new StateObject(client);
            //string data = null;
            int i;

            try
            {
                while (ThreadRun && (i = stream.Read(so.Buffer, 0, so.BufferSize)) != 0)
                {
                    // 수신 이벤트 처리
                    SocketReceiveEventArgs rev = new SocketReceiveEventArgs(id, i, so.Buffer);
                    Received(rev);


/*                  // 수신 확인 테스트용
 *                  data = System.Text.Encoding.UTF8.GetString(so.Buffer, 0, i);
 *                  updateStatusInfo("수신:" + data);
 *                  // Process the data sent by the client.
 *                  data = data.ToUpper();
 *
 *                  byte[] msg = System.Text.Encoding.UTF8.GetBytes(data);
 *
 *                  // Send back a response.
 *                  stream.Write(msg, 0, msg.Length);
 */
                }

                /*      // 패킷에 의한 전송
                 *          if (client.GetStream().CanRead)
                 *          {
                 *              IFormatter formatter = new BinaryFormatter();
                 *
                 *              DataPacket packet = new DataPacket();
                 *              packet = (DataPacket)formatter.Deserialize(stream);
                 *
                 *              Name = packet.Name;
                 *              Subject = packet.Subject;
                 *              Grade = packet.Grade;
                 *              Memo = packet.Memo;
                 *              SendTime = packet.SendTime;
                 *
                 *              time = DateTime.Now - SendTime;
                 *
                 *              updateStatusInfo(string.Format("[{0}] data received", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")));
                 *          }
                 */
            }
            catch (SocketException se)
            {
                SocketErrorEventArgs eev = new SocketErrorEventArgs(this.id, se);
                ErrorOccured(eev);
                //                Debug.WriteLine("ServerSocket->clientThread SocketException" + se.Message);
            }
            catch (Exception err)
            {
                SocketErrorEventArgs eev = new SocketErrorEventArgs(this.id, err);
                ErrorOccured(eev);
                //                Debug.WriteLine("ServerSocket->clientThread Exception" + err.Message);
            }
            finally
            {
                try
                {
                    if (stream != null)
                    {
                        stream.Close();
                        stream = null;
                    }
                    if (client != null)
                    {
                        // Client 접속 IP 와 고유번호를 가저온다.
                        string remoteip = client.Client.RemoteEndPoint.ToString();
                        // 해당 IP가 등록 되어 있는지 확인
                        if (RemoteClients.ContainsKey(remoteip))
                        {
                            RemoteClients.Remove(remoteip);
                        }
                        client.Close();
                        client = null;
                    }
                }
                catch (Exception err)
                {
                    SocketErrorEventArgs eev = new SocketErrorEventArgs(this.id, err);
                    ErrorOccured(eev);
                    //                    Debug.WriteLine("error:" + err.Message);
                }
            }
            updateStatusInfo(string.Format("[{0}] disconnted", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")));

            // 2. 데이타 표시하기

            /*
             *          Invoke((MethodInvoker)delegate
             *          {
             *              int count = listView1.Items.Count;
             *              count++;
             *
             *              ListViewItem i = new ListViewItem();
             *              i.Text = count.ToString();
             *              i.SubItems.Add(Name);
             *              i.SubItems.Add(Subject);
             *              i.SubItems.Add(Grade.ToString());
             *              i.SubItems.Add(Memo);
             *              i.SubItems.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
             *              i.SubItems.Add(string.Format("{0}.{1} seconds", time.Seconds.ToString(), time.Milliseconds.ToString()));
             *              listView1.Items.Add(i);
             *
             *              listView1.Items[this.listView1.Items.Count - 1].EnsureVisible();
             *          });
             */
        }