Exemplo n.º 1
0
    public void Send(byte[] send_data)
    {
        AsyncObject ao = new AsyncObject(1);

        //data send
        m_client.BeginSend(send_data, 0, send_data.Length, SocketFlags.None, m_fnSendHandler, ao);
    }
Exemplo n.º 2
0
        private void handleClientConnectionRequest(IAsyncResult ar)
        {
            Socket sockClient;

            try {
                // 클라이언트의 연결 요청을 수락합니다.
                sockClient = m_ServerSocket.EndAccept(ar);
            } catch (Exception ex) {
                Console.WriteLine("연결 수락 도중 오류 발생! 메세지: {0}", ex.Message);
                return;
            }

            // 4096 바이트의 크기를 갖는 바이트 배열을 가진 AsyncObject 클래스 생성
            AsyncObject ao = new AsyncObject(4096);

            // 작업 중인 소켓을 저장하기 위해 sockClient 할당
            ao.WorkingSocket = sockClient;

            // 클라이언트 소켓 저장
            m_ConnectedClient = sockClient;

                        try {
                             // 비동기적으로 들어오는 자료를 수신하기 위해 BeginReceive 메서드 사용!
                             sockClient.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, m_fnReceiveHandler, ao);
            } catch (Exception ex) {
                // 예외가 발생하면 예외 정보 출력 후 함수를 종료한다.
                Console.WriteLine("자료 수신 대기 도중 오류 발생! 메세지: {0}", ex.Message);
                return;
            }
        }
Exemplo n.º 3
0
        private void handleDataSend(IAsyncResult ar)
        {
            // 넘겨진 추가 정보를 가져옵니다.
            AsyncObject ao = (AsyncObject)ar.AsyncState;
                        
                        // 보낸 바이트 수를 저장할 변수 선언
                        Int32 sentBytes;

                        
                        try {
                            // 자료를 전송하고, 전송한 바이트를 가져옵니다.
                                sentBytes = ao.WorkingSocket.EndSend(ar);
            } catch (Exception ex) {
                // 예외가 발생하면 예외 정보 출력 후 함수를 종료한다.
                Console.WriteLine("자료 송신 도중 오류 발생! 메세지: {0}", ex.Message);
                                return;

                            
            }
                     
                        if(sentBytes > 0)
            {
                             // 여기도 마찬가지로 보낸 바이트 수 만큼 배열 선언 후 복사한다.
                             Byte[] msgByte = new Byte[sentBytes];
                             Array.Copy(ao.Buffer, msgByte, sentBytes);

                Console.WriteLine("메세지 보냄: {0}", Encoding.UTF8.GetString(msgByte));
                            
            }
        }
Exemplo n.º 4
0
    public void StartClient()
    {
        // Create a TCP/IP socket.
        Socket newsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

        isConnected = false;
        // Conncet to the remote endpoint
        try{
            m_client.Connect(serverIp, serverPort);
            isConnected = true;

            Application.LoadLevel("Login");
            Debug.Log("Coneected");
        }

        catch (Exception e) {
            isConnected = false;
            Debug.Log("UnConeected");
            Debug.Log(e.ToString());
        }

        if (isConnected)
        {
            AsyncObject ao = new AsyncObject(4096);
            ao.WorkingSocket = m_client;
            m_client.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, m_fnReceiveHandler, ao);
        }
    }
Exemplo n.º 5
0
        private void handleReceivedData(IAsyncResult ar)
        {
            AsyncObject ao = (AsyncObject)ar.AsyncState;
            int         recvBytes;

            try
            {
                recvBytes = ao.WorkingSocket.EndReceive(ar);
            }
            catch
            {
                return;
            }
            if (recvBytes > 0)
            {
                byte[] msgByte = new byte[recvBytes];
                Array.Copy(ao.Buffer, msgByte, recvBytes);
                connFrm.ConnectLoglistBox.Items.Add("메세지 받음 : " + Encoding.Unicode.GetString(msgByte));
                descripter.descript(Encoding.Unicode.GetString(msgByte));
            }
            try
            {
                ao.WorkingSocket.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, m_ReceiveHandler, ao);
            }
            catch (Exception ex)
            {
                connFrm.ConnectLoglistBox.Items.Add("수신 대기 도중 오류 발생 : " + ex.Message);
                return;
            }
        }
Exemplo n.º 6
0
        private void handleClientConnectionRequest(IAsyncResult ar)
        {
            Socket sockClient;

            try
            {
                sockClient = m_ServerSocket.EndAccept(ar);
                connFrm.ConnectLoglistBox.Items.Add("Client Connected!!");
                connFrm.connectReq = true;
                connFrm.setserverconnFlag();
                descripter = new Descripter(connFrm.parent);
            }
            catch (Exception ex)
            {
                //connFrm.ConnectLoglistBox.Items.Add("연결 수락 도중 오류 발생 : " + ex.Message);
                return;
            }
            AsyncObject ao = new AsyncObject(4096);

            ao.WorkingSocket  = sockClient;
            m_ConnectedClient = sockClient;
            try
            {
                sockClient.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, m_ReceiveHandler, ao);
            }
            catch (Exception ex)
            {
                connFrm.ConnectLoglistBox.Items.Add("수신 대기 도중 오류 발생 : " + ex.Message);
                return;
            }
        }
Exemplo n.º 7
0
        public void ConnectToServer()
        {
            hostPort       = Int32.Parse(connFrm.textBox1.Text);
            hostName       = connFrm.textBox2.Text;
            m_ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            bool isConnected = false;

            try
            {
                m_ClientSocket.Connect(new IPEndPoint(IPAddress.Parse(hostName), hostPort));
                isConnected = true;
            }
            catch
            {
                isConnected = false;
            }
            if (isConnected)
            {
                AsyncObject ao = new AsyncObject(4096);
                ao.WorkingSocket = m_ClientSocket;
                m_ClientSocket.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, m_ReceiveHandler, ao);
                connFrm.ConnectLoglistBox.Items.Add("연결 성공");
                connFrm.setclientconnFlag();
                descripter = new Descripter(connFrm.parent);
            }
            else
            {
                connFrm.ConnectLoglistBox.Items.Add("연결 실패");
            }
        }
Exemplo n.º 8
0
        void OnConnectToServer(object sender, EventArgs e)
        {
            if (mainSock.Connected)
            {
                MsgBoxHelper.Error("이미 연결되어 있습니다!");
                return;
            }

            int port;

            if (!int.TryParse(txtPort.Text, out port))
            {
                MsgBoxHelper.Error("포트 번호가 잘못 입력되었거나 입력되지 않았습니다.");
                txtPort.Focus();
                txtPort.SelectAll();
                return;
            }

            try { mainSock.Connect("172.16.52.226", port); }
            catch (Exception ex)
            {
                MsgBoxHelper.Error("연결에 실패했습니다!\n오류 내용: {0}", MessageBoxButtons.OK, ex.Message);
                return;
            }

            // 연결 완료되었다는 메세지를 띄워준다.
            AppendText(textBox1, "서버와 연결되었습니다.");

            // 연결 완료, 서버에서 데이터가 올 수 있으므로 수신 대기한다.
            AsyncObject obj = new AsyncObject(4096);

            obj.WorkingSocket = mainSock;
            mainSock.BeginReceive(obj.Buffer, 0, obj.BufferSize, 0, DataReceived, obj);
        }
Exemplo n.º 9
0
        public bool SendToOther(User other, Message message)
        {
            foreach (var it in Users)
            {
                if (it == other)
                {
                    continue;
                }

                AsyncObject ao = new AsyncObject(1);
                ao.Buffer        = message;
                ao.WorkingSocket = it.Socket;
                try
                {
                    it.Socket.BeginSend(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnSend, ao);
                }
                catch (Exception ex)
                {
                    ServerError?.Invoke(new ServerErrorEventArgs(ex, DateTime.Now, this));

                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 10
0
        private void HdlDataSend(IAsyncResult ar)
        {
            // 넘겨진 추가 정보를 가져옵니다.
            AsyncObject ao = (AsyncObject)ar.AsyncState;

            // 자료를 전송하고, 전송한 바이트를 가져옵니다.
            Int32 sentBytes = ao.WorkingSocket.EndSend(ar);

            try
            {
                // 자료를 전송하고, 전송한 바이트를 가져옵니다.
                sentBytes = ao.WorkingSocket.EndSend(ar);
            }
            catch (Exception ex)
            {
                // 예외가 발생하면 예외 정보 출력 후 함수를 종료한다.
                string str = "자료 송신 도중 오류 발생  !!\r\n";
                this.BeginInvoke(new SetTextCallBack(display_data), new object[] { str });
                return;
            }

            if (sentBytes > 0)
            {
                Byte[] msgByte = new Byte[sentBytes];
                Array.Copy(ao.Buffer, msgByte, sentBytes);

                string str = "메세지 보냄 : " + Encoding.Unicode.GetString(msgByte) + "\r\n";
                this.BeginInvoke(new SetTextCallBack(display_data), new object[] { str });
            }
        }
Exemplo n.º 11
0
        public void ReceivedFromServer(IAsyncResult ar)
        {
            try
            {
                AsyncObject obj = (AsyncObject)ar.AsyncState;

                int numReceived = obj.WorkingSocket.EndReceive(ar);

                if (numReceived <= 0)
                {
                    obj.WorkingSocket.Close();
                    return;
                }

                string txt = Encoding.UTF8.GetString(obj.Buffer).Trim('\0');

                System.Console.WriteLine("Messege From Server : " + txt);

                obj.ClearBuffer();

                obj.WorkingSocket.BeginReceive(obj.Buffer, 0, obj.BufferSize, SocketFlags.None, ReceivedFromServer, obj);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }
Exemplo n.º 12
0
        // 사용자로부터의 연결요청을 다루는 함수
        private void handleClientConnectionRequest(IAsyncResult ar)
        {
            Socket sockClient;

            try
            {
                sockClient = m_ServerSocket.EndAccept(ar);
            }
            catch (Exception ex)
            {
                Console.WriteLine("연결 수락 도중 오류 발생! 메세지: {0}", ex.Message);
                return;
            }

            AsyncObject ao = new AsyncObject(4096);

            ao.WorkingSocket  = sockClient;
            m_ConnectedClient = sockClient;

            try
            {
                sockClient.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, m_fnReceiveHandler, ao);
            }
            catch (Exception ex)
            {
                Console.WriteLine("자료 수신 대기 도중 오류 발생! 메세지: {0}", ex.Message);
                return;
            }
        }
Exemplo n.º 13
0
    void RecvCallback(System.IAsyncResult ar)
    {
        string response = string.Empty;

        try
        {
            AsyncObject ao   = (AsyncObject)ar.AsyncState;
            int         recv = ao.workSock.EndReceive(ar);
            if (recv > 0)
            {
                ao.sb.Append(Encoding.Unicode.GetString(ao.buf, 0, recv));
                ao.workSock.BeginReceive(ao.buf, 0, ao.buf.Length,
                                         SocketFlags.None, fncRecvHandler, ao);
            }
            else
            {
                if (ao.sb.Length > 1)
                {
                    response = ao.sb.ToString();
                }
            }
        }

        catch (Exception e)
        {
            Debug.Log(e.ToString());
        }
    }
Exemplo n.º 14
0
                public void SendMessage(String message)
        {
                         // 추가 정보를 넘기기 위한 변수 선언
                         // 크기를 설정하는게 의미가 없습니다.
                         // 왜냐하면 바로 밑의 코드에서 문자열을 유니코드 형으로 변환한 바이트 배열을 반환하기 때문에
                         // 최소한의 크기르 배열을 초기화합니다.
                        AsyncObject ao = new AsyncObject(1);
                     
                        // 문자열을 바이트 배열으로 변환
                        ao.Buffer = Encoding.UTF8.GetBytes(message);
                        
                        ao.WorkingSocket = m_ConnectedClient;
                     
                            // 전송 시작!
            try {
                             m_ConnectedClient.BeginSend(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, m_fnSendHandler, ao);

                            
            } catch (Exception ex) {
                             Console.WriteLine("전송 중 오류 발생!\n메세지: {0}", ex.Message);

                            
            }
                    
        }
Exemplo n.º 15
0
 void Update()
 {
     // 发送
     if (IsConnected && IsLogin)
     {
         if (sendQueue.Count > 0)
         {
             int count = 0;
             while (sendQueue.Count > 0 && count++ < MAX_SEND_COUNT)
             {
                 AsyncObject asyncObject = sendQueue.Dequeue();
                 _SendMessageAsyc(asyncObject.Opcode, asyncObject.Data, asyncObject.action);
             }
         }
     }
     else
     {
         if (needConnectOnce)
         {
             needConnectOnce = false;
             getServerListAndConnectServerAndLogin();                  //
         }
     }
     // 接收的处理
     if (invokeQueue.Count > 0)
     {
         lock (invokeQueue) {
             while (invokeQueue.Count > 0)
             {
                 AsyncObject asyncObject = invokeQueue.Dequeue();
                 asyncObject.action.Invoke(asyncObject.Opcode, asyncObject.Data);
             }
         }
     }
 }
Exemplo n.º 16
0
        private void handleDataSend(IAsyncResult ar)
        {
            // 넘겨진 추가 정보를 가져옵니다.
            AsyncObject ao = (AsyncObject)ar.AsyncState;

            // 보낸 바이트 수를 저장할 변수 선언
            Int32 sentBytes;

            try
            {
                // 자료를 전송하고, 전송한 바이트를 가져옵니다.
                sentBytes = ao.WorkingSocket.EndSend(ar);
            }
            catch (Exception ex)
            {
                // 예외가 발생하면 예외 정보 출력 후 함수를 종료한다.
                string str = "자료 송신 도중 오류 발생!\r\n";
                this.BeginInvoke(new SetTextCallBack(display_data), new object[] { str });

                return;
            }

            if (sentBytes > 0)
            {
                // 여기도 마찬가지로 보낸 바이트 수 만큼 배열 선언 후 복사한다.
                Byte[] msgByte = new Byte[sentBytes];
                Array.Copy(ao.Buffer, msgByte, sentBytes);

                string str = "메세지 보냄: " + textBox_sendtxt.Text + "\r\n";
                this.BeginInvoke(new SetTextCallBack(display_data), new object[] { str });
            }
        }
Exemplo n.º 17
0
        void OnConnectToServer(object sender, EventArgs e)
        {
            if (mainSock.Connected)
            {
                MsgBoxHelper.Error("이미 연결되어 있습니다!");
                return;
            }
            int port = 15000;    //고정

            nameID = txtID.Text; //ID
            AppendText(txtHistory, string.Format("서버: @{0}, port: 15000, ID: @{1}",
                                                 txtAddress.Text, nameID));
            try
            {
                mainSock.Connect(txtAddress.Text, port);
            }
            catch (Exception ex)
            {
                MsgBoxHelper.Error("연결에 실패했습니다!\n오류 내용: {0}",
                                   MessageBoxButtons.OK, ex.Message);
                return;
            }
            // 연결 완료되었다는 메세지를 띄워준다.
            AppendText(txtHistory, "서버와 연결되었습니다.");
            // 연결 완료, 서버에서 데이터가 올 수 있으므로 수신 대기한다.
            AsyncObject obj = new AsyncObject(4096);

            obj.WorkingSocket = mainSock;
            mainSock.BeginReceive(obj.Buffer, 0, obj.BufferSize, 0,
                                  DataReceived, obj);
        }
Exemplo n.º 18
0
        private void send(IAsyncResult ar)
        {
            AsyncObject ao = (AsyncObject)ar.AsyncState;

            int sendBytes;

            try
            {
                sendBytes = ao.WorkingSocket.EndSend(ar);
            }
            catch (Exception ex)
            {
                if (ClientError != null)
                {
                    ClientError(new ClientErrorEventArgs(ex, DateTime.Now, this));
                }

                return;
            }

            if (sendBytes > 0)
            {
                byte[] msgByte = new byte[sendBytes];
                Array.Copy(ao.Buffer, msgByte, sendBytes);

                Message msg = new Message(msgByte);

                if (SendMessage != null)
                {
                    SendMessage(new MessageEventArgs(msg, ao.WorkingSocket));
                }
            }
        }
Exemplo n.º 19
0
        public void ConnectToServer(String hostName, UInt16 hostPort)
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            Boolean isConnected = false;

            try
            {
                clientSocket.Connect(hostName, hostPort);
                isConnected = true;
            }
            catch
            {
                isConnected = false;
            }

            if (isConnected)
            {
                AsyncObject asyncObject = new AsyncObject(4096);
                asyncObject.workingSocket = clientSocket;
                clientSocket.BeginReceive(asyncObject.buffer, 0, asyncObject.buffer.Length, SocketFlags.None, fnReceiveHandler, asyncObject);

                Console.WriteLine("연결 성공");
            }
            else
            {
                Console.WriteLine("연결 실패");
            }
        }
Exemplo n.º 20
0
        public void ConnectSockets(Socket socketC)
        {
            if (socketC.Connected)
            {
                MessageBox.Show("이미 연결중입니다.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            int port;

            if (!int.TryParse(serverF.serverForm.txtPort.Text, out port))
            {
                MessageBox.Show("포트번호가 유효하지 않습니다.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                serverF.serverForm.txtPort.Focus();
                serverF.serverForm.txtPort.SelectAll();
                return;
            }
            try { socketC.Connect(serverF.serverForm.txtAdd.Text, port); }

            catch (Exception ev)
            {
                MessageBox.Show(ev.Message, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Appendtext(serverF.serverForm.txtLog, "서버 연결됨");

            AsyncObject obj = new AsyncObject(4096);

            obj.WorkingSocket = socketC;
            //AsyncCallBack
            socketC.BeginReceive(obj.Buffer, 0, obj.BufferSize, 0, DataReceived, obj);
        }
Exemplo n.º 21
0
        public void DataReceived(IAsyncResult ar)
        {
            AsyncObject obj = (AsyncObject)ar.AsyncState;
            //IAsyncResult
            int received = obj.WorkingSocket.EndReceive(ar);

            //받은 데이터가 없을때
            if (received <= 0)
            {
                obj.WorkingSocket.Close();
                return;
            }
            //받은걸 UTF8로 인코딩
            string text = Encoding.UTF8.GetString(obj.Buffer);

            // 0x01 기준으로 짜른다. 보낼떄 "0x01"을 데이터 사이에 집어 넣어서
            // tokens[0] - 보낸 사람 IP
            // tokens[1] - 보낸 메세지
            string[] tokens = text.Split('#');
            string   ip     = tokens[0];
            string   msg    = tokens[1];


            Appendtext(serverF.serverForm.txtLog, string.Format("[server에게 받음]{0} : {1}", ip, msg));

            //데이터 수신 후 버퍼 비워주기
            obj.ClearBuffer();
            //다시 수신대기
            obj.WorkingSocket.BeginReceive(obj.Buffer, 0, 4096, 0, DataReceived, obj);
        }
Exemplo n.º 22
0
    private void handleDataRecive(IAsyncResult ar)
    {
        Debug.Log("Recevie");
        AsyncObject ao = (AsyncObject)ar.AsyncState;

        Int32 recvBytes;

        try{
            recvBytes = ao.WorkingSocket.EndReceive(ar);
        }catch {
            return;
        }

        if (recvBytes > 0)
        {
            Byte[] msgByte = new Byte[recvBytes];
            Array.Copy(ao.Buffer, msgByte, recvBytes);
        }

        try{
            ao.WorkingSocket.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, m_fnReceiveHandler, ao);
        }catch {
            return;
        }
    }
Exemplo n.º 23
0
    void RecvCallback(System.IAsyncResult ar)
    {
        string      content = string.Empty;
        AsyncObject ao      = (AsyncObject)ar.AsyncState;
        int         recv    = ao.workSock.EndReceive(ar);

        if (recv > 0)
        {
            ao.sb.Append(Encoding.Unicode.GetString(ao.buf, 0, recv));
            ao.workSock.BeginReceive(ao.buf, 0, ao.buf.Length,
                                     SocketFlags.None, fncRecvHandler, ao);

            content = state.sb.ToString();
            if (content.IndexOf("<EOF>") > -1)
            {
                // 모든 데이터가 클라이언트로부터 도착
                // 클라이언트 화면에 디스플레이한다.
                SendMsg(handler, content);
            }
            else
            {
                ao.workSock.BeginReceive(ao.buf, 0, ao.buf.Length,
                                         SocketFlags.None, fncRecvHandler, ao);
            }
        }
    }
Exemplo n.º 24
0
    public void OnConnectToServer(string ipstr, string portstr)
    {
        if (_mainSock.Connected)
        {
            Debug.Log("이미 연결 되어있습니다.");
            return;
        }

        int port;

        if (!int.TryParse(portstr, out port))
        {
            Debug.Log("포트 번호가 잘못 입력되었거나 입력 되지 않았습니다.");
            return;
        }

        try
        {
            _mainSock.Connect(ipstr, port);
        }
        catch (System.Exception ex)
        {
            Debug.Log(string.Format("연결에 실패 했습니다. 오류 내용 : {0}", ex.Message));
            return;
        }

        AsyncObject obj = new AsyncObject(1024);

        obj.WorkingSocket = _mainSock;
        _mainSock.BeginReceive(obj.Buffer, 0, obj.BufferSize, 0, StreamReceive, obj);
    }
Exemplo n.º 25
0
        private void handleDataReceive(IAsyncResult ar)
        {
            AsyncObject asyncObject = ar.AsyncState as AsyncObject;
            Int32       receiveBytes;

            try
            {
                receiveBytes = asyncObject.workingSocket.EndReceive(ar);
            }
            catch
            {
                return;
            }

            if (receiveBytes > 0)
            {
                Byte[] msgByte = new Byte[receiveBytes];
                Array.Copy(asyncObject.buffer, msgByte, receiveBytes);

                Console.WriteLine($"메시지 받음: {Encoding.Unicode.GetString(msgByte)}");
            }

            try
            {
                asyncObject.workingSocket.BeginReceive(asyncObject.buffer, 0, asyncObject.buffer.Length, SocketFlags.None, fnReceiveHandler, asyncObject);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"자료 수신 대기 도중 오류 발생! {ex.Message}");
                return;
            }
        }
Exemplo n.º 26
0
        private void send_command(Command_Server command_code, object data)
        {
            if (Unit_No == -1)
            {
                return;
            }
            AsyncObject ao = new AsyncObject(1);

            command_data_server CD = new command_data_server(Unit_No, command_code, data);

            // 문자열을 바이트 배열으로 변환

            //ao.Buffer = GZipCompress.Compress(Encoding.Unicode.GetBytes(JsonConvert.SerializeObject(CD)));
            ao.Buffer = Data_structure.Combine(Encoding.Unicode.GetBytes("^^^"), GZipCompress.Compress(Encoding.Unicode.GetBytes(JsonConvert.SerializeObject(CD))));

            ao.WorkingSocket = m_ClientSocket;
            // 전송 시작!
            try
            {
                m_ClientSocket.BeginSend(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, m_fnSendHandler, ao);
            }
            catch (Exception ex)
            {
                Console.WriteLine("SENDING ERROR: {0}", ex.Message);
                // 서버와 연결이 끊기면 여기서 문제가 생긴다.
                Make_Client_Event(Unit_Event_Type.Server_Connection_Broken, 0);
                Connected = false;
            }
        }
Exemplo n.º 27
0
        private static void Thread_Responser_()
        {
            command_data_server CMD;


            while (Connected)
            {
                while (Responser_Q.Count > 0)
                {
                    lock (Responser_Q)
                    {
                        CMD = (command_data_server)Responser_Q.Dequeue();
                    }
                    try
                    {
                        AsyncObject ao = new AsyncObject(1);
                        // 문자열을 바이트 배열으로 변환
                        //ao.Buffer = GZipCompress.Compress(Encoding.Unicode.GetBytes(JsonConvert.SerializeObject(CMD)));
                        ao.Buffer        = Data_structure.Combine(Encoding.Unicode.GetBytes("^^^"), GZipCompress.Compress(Encoding.Unicode.GetBytes(JsonConvert.SerializeObject(CMD))));
                        ao.WorkingSocket = m_ClientSocket;

                        ao.WorkingSocket.BeginSend(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, m_fnSendHandler, ao);
                    }
                    catch (Exception ex)
                    {
                        Console.Write("Error Send Message [ Command : {0}, data : {1},  receiver]", CMD.Command_code.ToString(), CMD.data != null ? CMD.data.ToString() : "", CMD.Sender.ToString());
                        Console.Write("Error String: {0}", ex);
                    }
                }
                Thread.Sleep(100);
            }
        }
Exemplo n.º 28
0
        public void Start(string host_address, ushort host_port)
        {
            _ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            bool join = false;

            try
            {
                _ClientSocket.Connect(host_address, host_port);

                join = true;
            }
            catch (Exception ex)
            {
                if (ClientError != null)
                {
                    ClientError(new ClientErrorEventArgs(ex, DateTime.Now, this));
                }

                join = false;
            }

            _Connected = join;

            if (join)
            {
                AsyncObject ao = new AsyncObject(4096);
                ao.WorkingSocket = _ClientSocket;
                _ClientSocket.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnReceiveHandler, ao);
            }
        }
Exemplo n.º 29
0
        void DataReceived(IAsyncResult ar)
        {
            // BeginReceive에서 추가적으로 넘어온 데이터를 AsyncObject 형식으로 변환한다.
            AsyncObject obj = (AsyncObject)ar.AsyncState;
            // 데이터 수신을 끝낸다.
            int received = obj.WorkingSocket.EndReceive(ar);

            // 받은 데이터가 없으면(연결끊어짐) 끝낸다.
            if (received <= 0)
            {
                obj.WorkingSocket.Close();
                return;
            }
            // 텍스트로 변환한다.
            string text = Encoding.UTF8.GetString(obj.Buffer);

            // : 기준으로 짜른다.
            // tokens[0] - 보낸 사람 ID, tokens[1] - 보낸 메세지
            string[] tokens = text.Split(':');
            string   id     = tokens[0];
            string   msg    = tokens[1];

            // 텍스트박스에 추가해준다.
            // 비동기식으로 작업하기 때문에 폼의 UI 스레드에서 작업을 해줘야 한다.
            // 따라서 대리자를 통해 처리한다.
            AppendText(txtHistory, string.Format("[받음]{0}: {1}", id, msg));
            // 클라이언트에선 데이터를 전달해줄 필요가 없으므로 바로 수신 대기한다.
            // 데이터를 받은 후엔 다시 버퍼를 비워주고 같은 방법으로 수신을 대기한다.
            obj.ClearBuffer();
            // 수신 대기
            obj.WorkingSocket.BeginReceive(obj.Buffer, 0, 4096, 0, DataReceived, obj);
        }
Exemplo n.º 30
0
        private void AcceptCompleted(object sender, SocketAsyncEventArgs e)
        {
            Socket client = e.AcceptSocket;

            AsyncObject obj = new AsyncObject(4096);

            obj.WorkingSocket = client;

            // 클라이언트가 접속하면 클라이언트 소켓을 리스트에 추가
            connectedClients.Add(client);

            if (connectedClients != null)
            {
                AppendText(string.Format("Connected with client(@ {0})", client.RemoteEndPoint));

                // 리시브 인스턴스 생성
                // 데이터 버퍼 설정
                // 소켓과 연결된 클라이언트(사용자) 개체 설정
                SocketAsyncEventArgs AsyncEvent = new SocketAsyncEventArgs();
                AsyncEvent.SetBuffer(obj.Buffer, 0, 4096);
                AsyncEvent.UserToken = connectedClients;
                // 클라이언트에게서 넘어온 데이터를 받았을 때 이벤트
                // 클라이언트 데이터 수신 시작
                AsyncEvent.Completed += new EventHandler <SocketAsyncEventArgs>(ReceiveCompleted);
                obj.WorkingSocket.ReceiveAsync(AsyncEvent);
            }

            // 소켓 초기화
            // 다시 클라이언트 접속 대기
            e.AcceptSocket = null;
            mainSocket.AcceptAsync(e);
        }
Exemplo n.º 31
0
        public void SendToServer(Message message)
        {
            AsyncObject ao = new AsyncObject(1);
            ao.Buffer = message;
            ao.WorkingSocket = _ClientSocket;

            try
            {
                _ClientSocket.BeginSend(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnSendHandler, ao);
            }
            catch (Exception ex)
            {
                if (ClientError != null)
                    ClientError(new ClientErrorEventArgs(ex, DateTime.Now, this));

                return;
            }
        }
Exemplo n.º 32
0
        public void RecvProgIng(Object obj)
        {
            AsyncObject ao = new AsyncObject(1);

            byte[] bytes = new byte[4096];
            int vv = 1;
            int MaxSize = (Int32)obj;
            int nBytes = MaxSize;

            Sendtotalbytes = 0L;

            this.listBoxServFileForm.Items.Add("파일수신 시작");
            Thread.Sleep(50);
            while (fsRecv.Length > 0)
            {
                Sendtotalbytes = fsRecv.Length;
                vv = (int)(Sendtotalbytes * 100 / MaxSize);
                SetServProgBar(vv);
                SetServLabel(vv + " %");

                if (fsRecv.Length >= MaxSize && vv >= 100)
                {
                    while (this.progressBarAsyncServFileTrans.Value != vv)
                    {
                        SetServProgBar(vv);
                        SetServLabel(vv + " %");
                    }

                    fsRecv.Flush();
                    fsRecv.Close();
                    fsRecv.Dispose();
                    break;
                }
            }
            this.listBoxServFileForm.Items.Add("파일수신 완료");
        }
        //---------------------------------------------------------------------------------------//
        /// <summary>
        /// 
        /// </summary>
        /// <returns>bool</returns>
        public override bool Initialise()
        {
            const String methodName = "Initialise";
            Logfile.WriteCalled(logLevel, STR_ClassName, methodName);

            bool success = false;

            try
            {
                this.disposed = false;

                /*
                 * Open a connection to the specified IP address and port
                 */
                this.tcpClient = new TcpClient();
                this.tcpClient.Connect(this.ipAddress, this.port);

                /*
                 * Create async object for TcpClient receive callback
                 */
                this.asyncObject = new AsyncObject();
                this.asyncObject.tcpClientStream = this.tcpClient.GetStream();

                /*
                 * Begin receiving data from the network
                 */
                this.asyncObject.tcpClientStream.BeginRead(asyncObject.receiveBuffer, 0, AsyncObject.BUFFER_SIZE,
                    new AsyncCallback(TcpClientReceiveCallback), asyncObject);

                /*
                 * Get the firmware version and display
                 */
                String hardwareFirmwareVersion = this.GetHardwareFirmwareVersion();
                this.WriteLine(LineNumber.One, DeviceSerialLcd.ClassName);
                this.WriteLine(LineNumber.Two, hardwareFirmwareVersion);

                /*
                 * Ensure data capture is stopped
                 */
                this.StopCapture();

                success = true;
            }
            catch (Exception ex)
            {
                Logfile.WriteError(ex.Message);
            }

            Logfile.WriteCompleted(logLevel, STR_ClassName, methodName,
                    String.Format(STRLOG_Success_arg, success));

            return success;
        }
Exemplo n.º 34
0
        public void SendProgIng()
        {
            AsyncObject ao = new AsyncObject(1);

            byte[] bytes = new byte[4096];
            byte[] revbytes = new byte[8];
            int vv = 1;
            int nBytes = 0;

            Sendtotalbytes = 0L;

            //string[] str = Encoding.UTF8.GetString(revbytes).Split('/');

            //if (str[0] != "OK")
            //{
            //    MessageBox.Show("에러 : 파일정보 불량");
            //    this.listBoxServFileForm.Items.Add("에러 : 파일정보 불량 ");
            //    return;
            //}
            //else
            this.listBoxServFileForm.Items.Add("파일전송 시작");

            while ((nBytes = fsTrans.Read(bytes, 0, bytes.Length)) > 0)
            {
                if (socketFileSend != null && socketFileSend.Connected)
                {
                    socketFileSend.Send(bytes, nBytes, 0);
                }

                ao.buffer = bytes;
                ao.workSocket = socketFileSend;
                Sendtotalbytes += nBytes;
                vv = (int)(Sendtotalbytes * 100 / fsTrans.Length);
                SetServProgBar(vv);
                SetServLabel(vv + " %");
            }
            fsTrans.Close();
            fsTrans.Dispose();
            this.listBoxServFileForm.Items.Add("파일전송 완료");
        }
Exemplo n.º 35
0
        //---------------------------------------------------------------------------------------//
        public override bool Initialise()
        {
            const string STRLOG_MethodName = "Initialise";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            bool success = false;

            //
            // Do base class initialisation first
            //
            base.Initialise();

            //
            // Check if this is first-time initialisation
            //
            if (this.initialised == false)
            {
                this.statusMessage = STRLOG_Initialising;

                //
                // Nothing to do here
                //

                //
                // First-time initialisation is complete
                //
                this.initialised = true;
            }

            //
            // Initialisation that must be done each time the equipment is powered up
            //
            try
            {
                //
                // Create TCP client connection to the SerialLCD
                //
                Logfile.Write(STRLOG_CreatingTcpClient);
                this.tcpClient = new TcpClient(this.ipaddr, this.port);
                this.tcpClientStream = this.tcpClient.GetStream();

                this.disposed = false;

                //
                // Create async object for TCP client callback
                //
                this.asyncObject = new AsyncObject();
                this.asyncObject.tcpClientStream = this.tcpClientStream;

                //
                // Begin receiving data from the SerialLCD on the network
                //
                this.tcpClientStream.BeginRead(this.asyncObject.receiveBuffer, 0, AsyncObject.BUFFER_SIZE,
                    new AsyncCallback(ReceiveCallback), this.asyncObject);

                //
                // Get the firmware version and display
                //
                string firmwareVersion = this.GetHardwareFirmwareVersion();
                this.WriteLine(1, STRLOG_ClassName);
                this.WriteLine(2, firmwareVersion);

                //
                // Ensure data capture is stopped
                //
                this.StopCapture();

                //
                // Initialisation is complete
                //
                this.online = true;
                this.statusMessage = StatusCodes.Ready.ToString();

                success = true;
            }
            catch (Exception ex)
            {
                Logfile.WriteError(ex.Message);
                this.Close();
            }

            string logMessage = STRLOG_Success + success.ToString();

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return success;
        }
        //---------------------------------------------------------------------------------------//
        /// <summary>
        /// 
        /// </summary>
        /// <returns>bool</returns>
        public override bool Initialise()
        {
            const String methodName = "Initialise";
            Logfile.WriteCalled(logLevel, STR_ClassName, methodName);

            bool success = false;

            try
            {
                this.disposed = false;

                /*
                 * Open a connection to the specified IP address and port
                 */
                Logfile.Write(STRLOG_OpeningTcpClientConnection);
                this.tcpClient = new TcpClient();
                this.tcpClient.Connect(this.ipAddress, this.port);

                /*
                 * Create async object for TcpClient receive callback
                 */
                this.asyncObject = new AsyncObject();
                this.asyncObject.tcpClientStream = this.tcpClient.GetStream();

                /*
                 * Begin receiving data from the network
                 */
                this.asyncObject.tcpClientStream.BeginRead(asyncObject.receiveBuffer, 0, AsyncObject.BUFFER_SIZE,
                    new AsyncCallback(TcpClientReceiveCallback), asyncObject);

                /*
                 * Set interface to Serial mode, retry if necessary
                 */
                for (int i = 0; i < 5; i++)
                {
                    if ((success = this.SetInterfaceMode(InterfaceMode.Serial)) == true)
                    {
                        break;
                    }

                    Delay.MilliSeconds(500);
                    Trace.Write('?');
                }

                /*
                 * Configure device
                 */
                if (this.Configure() == false)
                {
                    throw new ApplicationException(this.lastError);
                }

                success = true;
            }
            catch (Exception ex)
            {
                Logfile.WriteError(ex.Message);
            }

            Logfile.WriteCompleted(logLevel, STR_ClassName, methodName,
                    String.Format(STRLOG_Success_arg, success));

            return success;
        }
        //-------------------------------------------------------------------------------------------------//
        public override bool Initialise(bool configure)
        {
            const string STRLOG_MethodName = "Initialise";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            bool success = false;

            //
            // Do base class initialisation first
            //
            base.Initialise(configure);

            //
            // Check if this is first-time initialisation
            //
            if (this.initialised == false)
            {
                this.statusMessage = STRLOG_Initialising;

                //
                // Nothing to do here
                //

                //
                // First-time initialisation is complete
                //
                this.initialised = true;
            }

            //
            // Initialisation that must be done each time the equipment is powered up
            //
            try
            {
                //
                // Create TCP client connection to the ST360Counter
                //
                Logfile.Write(STRLOG_CreatingTcpClient);
                this.tcpClient = new TcpClient(this.ipaddr, this.port);
                this.tcpClientStream = this.tcpClient.GetStream();

                //
                // There is now some disposing to do
                //
                this.disposed = false;

                //
                // Create async object for TCP client callback
                //
                this.asyncObject = new AsyncObject();
                this.asyncObject.tcpClientStream = this.tcpClientStream;

                //
                // Begin receiving data from the ST360Counter on the network
                //
                this.tcpClientStream.BeginRead(this.asyncObject.receiveBuffer, 0, AsyncObject.BUFFER_SIZE,
                    new AsyncCallback(ReceiveCallback), this.asyncObject);

                //
                // Set interface to Serial mode, retry if necessary
                //
                for (int i = 0; i < 5; i++)
                {
                    if ((success = this.SetInterfaceMode(Commands.InterfaceSerial)) == true)
                    {
                        break;
                    }

                    Thread.Sleep(500);
                    Trace.Write('?');
                }
                if (success == false)
                {
                    throw new Exception(this.GetLastError());
                }

                //
                // Check if full configuration is required, always will be unless developing/debugging
                //
                if (configure == true)
                {
                    this.Configure();
                }

                //
                // Initialisation is complete
                //
                this.online = true;
                this.statusMessage = StatusCodes.Ready.ToString();

                success = true;
            }
            catch (Exception ex)
            {
                Logfile.WriteError(ex.Message);
                this.Close();
            }

            string logMessage = STRLOG_Online + this.online.ToString();

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return success;
        }
Exemplo n.º 38
0
        public bool SendToUser(User user, Message message)
        {
            AsyncObject ao = new AsyncObject(1);
            ao.Buffer = message;
            ao.WorkingSocket = user.Socket;
            try
            {
                user.Socket.BeginSend(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnSendHandler, ao);
            }
            catch (Exception ex)
            {
                if (ServerError != null)
                    ServerError(new ServerErrorEventArgs(ex, DateTime.Now, this));

                return false;
            }

            return true;
        }
Exemplo n.º 39
0
        public void Start(string host_address, ushort host_port)
        {
            _ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            bool join = false;
            try
            {
                _ClientSocket.Connect(host_address, host_port);

                join = true;
            }
            catch (Exception ex)
            {
                if (ClientError != null)
                    ClientError(new ClientErrorEventArgs(ex, DateTime.Now, this));

                join = false;
            }

            _Connected = join;

            if (join)
            {
                AsyncObject ao = new AsyncObject(4096);
                ao.WorkingSocket = _ClientSocket;
                _ClientSocket.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnReceiveHandler, ao);
            }
        }
Exemplo n.º 40
0
        public bool SendToOther(User other, Message message)
        {
            foreach (var it in Users)
            {
                if (it == other) continue;

                AsyncObject ao = new AsyncObject(1);
                ao.Buffer = message;
                ao.WorkingSocket = it.Socket;
                try
                {
                    it.Socket.BeginSend(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnSendHandler, ao);
                }
                catch (Exception ex)
                {
                    if (ServerError != null)
                        ServerError(new ServerErrorEventArgs(ex, DateTime.Now, this));

                    return false;
                }
            }

            return true;
        }
Exemplo n.º 41
0
        private void connect(IAsyncResult ar)
        {
            Socket client;
            try
            {
                client = _ServerSocket.EndAccept(ar);
            }
            catch (Exception ex)
            {
                if (ServerError != null)
                    ServerError(new ServerErrorEventArgs(ex, DateTime.Now, this));

                return;
            }

            AsyncObject ao = new AsyncObject(4096);
            ao.WorkingSocket = client;

            User user = new User();
            user.Socket = client;
            user.IP = ((IPEndPoint)client.RemoteEndPoint).Address.ToString();
            user.Port = ((IPEndPoint)client.RemoteEndPoint).Port;
            user.Server = this;
            user.Guid = null;
            Users.Add(user);

            Message info = new Message() { Type = MessageType.Info, Text = Data.ServerName };
            SendToUser(user, info);

            info = new Message() { Type = MessageType.Info, Text = Data.MaxUserCount.GetValueOrDefault().ToString() };
            SendToUser(user, info);

            //info = new Message() { Type = MessageType.Info, Text = Utility.ToBase64(Data.ServerImage, ImageFormat.Png) };
            //SendToUser(user, info);

            try
            {
                client.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnReceiveHandler, ao);
            }
            catch (Exception ex)
            {
                if (ServerError != null)
                    ServerError(new ServerErrorEventArgs(ex, DateTime.Now, this));

                return;
            }
        }