Exemple #1
0
        public async Task <int> ReadAsync(BytesSegment bs)
        {
            var pos     = 0;
            var curnode = latestMsg;

            if (curnode == null || curnode.tlen == 0)
            {
                curnode = (await MsgStream.RecvMsgR(null)).Data;
                if (curnode == null)
                {
                    return(0);
                }
            }
            do
            {
                if (curnode.len > 0)
                {
                    var size = Math.Min(bs.Len, curnode.len);
                    Buffer.BlockCopy(curnode.bytes, curnode.offset, bs.Bytes, bs.Offset + pos, size);
                    curnode.SubSelf(size);
                    pos += size;
                }
            } while (pos < bs.Len && (curnode = curnode.nextNode) != null);
            if (curnode == null || curnode.tlen == 0)
            {
                latestMsg = null;
            }
            else
            {
                latestMsg = curnode;
            }
            return(pos);
        }
Exemple #2
0
        private void sendClipboardDatas()
        {
            //MessageBox.Show("Sending clipboard to server:" + i.ToString() + " .\nYou will be advised when the transfer is completed.", "Starting Transfer", MessageBoxButtons.OK, MessageBoxIcon.Information);

            Socket s = _host.ds(i);

            if (s == null)
            {
                EnableCB();
                return;
            }

            IDataObject clipboardData = Clipboard.GetDataObject();

            string[] formats = clipboardData.GetFormats();

            try{
                foreach (string format in formats)
                {
                    //Console.WriteLine("Analizing clipboard. FORMAT FOUND: " + format);
                    if (format == DataFormats.FileDrop)
                    {
                        continue;
                    }
                    MsgStream.Send(new DataMsgCBP(format, clipboardData.GetData(format)), _host.ds(i));
                }

                /* SENDING FILE TYPE */

                if (Clipboard.ContainsFileDropList())
                {
                    long size = ClipboardFiles.GetCBFilesSize();
                    if (size > ClipboardFiles.MaxSize)
                    {
                        if (MessageBox.Show("The size of clipboard's content is greater than MaxSize: " + ClipboardFiles.MaxSize
                                            + " \nConfirm the transfer?", "Closing Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                        {
                            EnableCB();
                            return;
                        }
                    }

                    MsgStream.Send(new InitFileCBP(), s);
                    ClipboardFiles.SendClipboardFiles(s);
                    MsgStream.Send(new StopFileCBP(), s);
                    ConfirmCBP m = (ConfirmCBP)MsgStream.Receive(s);
                }
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show("Ops...\nSomething goes wrong during Clipboard Transfer[on Sending].\nThe connection will be closed.\nTry again later.",
                                                     "Clipboard Transfer Error!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                this.DisconnectionReq();
                Console.WriteLine("Clipboard file transfer error: " + e.Message);
            }


            EnableCB();
            return;
        }
        //从stream中读取数据以初始化field
        public void Decode(MsgStream ms)
        {
            this.xxx = ms.Int;
            this.list.Clear();
            int ____COUNT___list = ms.Short;

            for (int i = 0; i < ____COUNT___list; i++)
            {
                this.list.Add(ms.Float);
            }
            ;
            this.lis1111t.Clear();
            int ____COUNT___lis1111t = ms.Short;

            for (int i = 0; i < ____COUNT___lis1111t; i++)
            {
                this.lis1111t.Add(ms.Vector3);
            }
            ;
            this.lis2312323t.Clear();
            int ____COUNT___lis2312323t = ms.Short;

            for (int i = 0; i < ____COUNT___lis2312323t; i++)
            {
                this.lis2312323t.Add(ms.Quaternion);
            }
            ;
            this.xxxxxx  = ms.Vector3;
            this.plsqsfq = ms.Quaternion;
            this.my_name = ms.String;
        }
 //从stream中读取数据以初始化field
 public void Decode(MsgStream ms)
 {
     this.id          = ms.Int;
     this.position    = ms.Vector3;
     this.yValue      = ms.Float;
     this.move        = ms.Byte;
     this.rotationAim = ms.Vector3;
     this.fightstate  = ms.Byte;
 }
Exemple #5
0
    private void ThreadFunction_Recv()
    {
        try
        {
            while (_thread_running && isConnected)
            {
                var bufraw = _inner_socket.Receive(ref _server_endpoint);
                if (bufraw.Length > 4)
                {
                    byte[] buf = Base.MemoryPool.Alloc(bufraw.Length - 4);    //new byte[bufraw.Length - 4];
                    Array.Copy(bufraw, 4, buf, 0, bufraw.Length - 4);
                    XOREncrypt.Decrypt(buf, bufraw.Length - 4);
                    MsgStream msg = MsgStream.Create(buf, bufraw.Length - 4);

                    if (msg.IsCustomCmd)
                    {
                        if (msg.CustomType == CustomMsgType.ping)
                        {
                            //服务器返回了 证明连接成功了
                            _IsConnected = true;
                            TimeSpan ts = DateTime.Now - mLastPingTime;//mLastPingTimes[idx];
                            mPing         = (int)(ts.TotalMilliseconds);
                            mLastPingTime = DateTime.Now;
                            //    this.LastSendPingTimestamp = Utils.GetTimestampSecondsInt();
                            msg.Dispose();
                            continue;
                        }
                    }
                    //服务器返回了 证明连接成功了
                    _IsConnected = true;
                    _recvQueue.Enqueue(msg);
                }
                else
                {
                    //<=4
                }
            }
        }
        catch (SocketException e)
        {
            Debug.Log("UdpSocket:" + e.Message + "   " + e.ErrorCode + "  " + e.NativeErrorCode + "  " + e.SocketErrorCode);
        }
        catch (Exception e)
        {
            Debug.Log("UdpSocket:" + e.Message);
        }
        this.Disconnected();
        while (_recvQueue.Empty() == false)
        {
            var x = _recvQueue.Dequeue();
            if (x != null)
            {
                x.Dispose();
            }
        }
        Debug.Log("[NetWork]:UdpSocket Recv Thread Close");
    }
Exemple #6
0
    /// <summary>
    /// 消息解码
    /// </summary>
    /// <param name="length"></param>
    private static void ReadBuffInfo(int length)
    {
        int PROTOLEN_BYTES = 4;//代表包头的int占用字节数

        byte[] edata = null;
        msgLength += length;
        while (true)
        {
            if (msgLength <= 0)
            {
                break;
            }
            MsgStream ms = new MsgStream();
            ms.SetReverse(true);
            ms.setReadIndex(offSet);
            if (ms.bytesAvailable(offSet + msgLength) >= PROTOLEN_BYTES)
            {
                int protolen = 0;
                ms.ReadInt(readData, ref protolen);//读取包头的4个字节
                if (ms.bytesAvailable(offSet + msgLength) >= protolen)
                {
                    int msgid = 0;
                    ms.ReadInt(readData, ref msgid);//读取代表协议号的4个字节
                    ms.Read(readData, offSet + PROTOLEN_BYTES + HEAD_LEN,
                            protolen - HEAD_LEN, ref edata);

                    CallOnRpcData(edata, msgid);//传出数据包
                    int progresslen = PROTOLEN_BYTES + protolen;
                    offSet    += progresslen;
                    msgLength -= progresslen;
                    if (buffSize - offSet - msgLength < readSize)
                    {
                        Buffer.BlockCopy(readData, offSet, readData, 0, msgLength);
                        offSet = 0;
                    }
                }
                else
                {
                    if (buffSize - offSet - msgLength < readSize)
                    {
                        Buffer.BlockCopy(readData, offSet, readData, 0, msgLength);
                        offSet = 0;
                    }
                    break;
                }
            }
            else
            {
                if (buffSize - offSet - msgLength < readSize)
                {
                    Buffer.BlockCopy(readData, offSet, readData, 0, msgLength);
                    offSet = 0;
                }
                break;
            }
        }
    }
Exemple #7
0
 public override void AddSendMsg(MsgStream msg)
 {
     if (!_thread_running || !isConnected)
     {
         msg.Dispose();
         return;
     }
     //   msg += "\0";
     _sendQueue.Enqueue(msg);
 }
Exemple #8
0
        private void Connect()
        {
            Socket tmpE = new Socket(SocketType.Stream, ProtocolType.Tcp); //event socket
            Socket tmpD = new Socket(SocketType.Stream, ProtocolType.Tcp); //clipboard socket
            object o    = null;

            try
            {
                Console.WriteLine("Connecting EventSocket To -> " + IP + ":" + EP.ToString());
                tmpE.Connect(IP, EP);

                /* Authentication on EventSocket*/

                MsgStream.Send(new AuthMsg(PSW), tmpE);
                o = MsgStream.Receive(tmpE);

                if ((o is AckMsg) && (((AckMsg)o).ack))
                {
                    Console.WriteLine("Connection completed successful on EventSocket.");
                }
                else
                {
                    throw new Exception();
                }


                Console.WriteLine("Connecting DataSocket To -> " + IP + ":" + DP.ToString());
                tmpD.Connect(IP, DP);

                /* Authentication on DataSocket */
                Console.WriteLine("Starting authentication protocol.");
                MsgStream.Send(new AuthMsg(PSW), tmpD);
                o = MsgStream.Receive(tmpD);

                if ((o is AckMsg) && (((AckMsg)o).ack))
                {
                    Console.WriteLine("Connection completed successful on DataSocket.");
                }
                else
                {
                    throw new Exception();
                }

                _host.es(tmpE, i);
                _host.ds(tmpD, i);
                this.Connected();
            }
            catch (Exception)
            {
                tmpE.Close();
                tmpD.Close();
                this.Disconnected();
            }
        }
        /////////////-----------dont modify follow code your modifications will be loss
        /////////////-----------dont modify follow code your modifications will be loss
        /////////////-----------dont modify follow code your modifications will be loss
        /////////////-----------dont modify follow code your modifications will be loss
        /////////////-----------dont modify follow code your modifications will be loss
        /////////////-----------dont modify follow code your modifications will be loss



        //---Auto Generate Code Start---
        //把该类的field 写入到stream中
        public void Encode(MsgStream ms)
        {
            ms.stream.WriteByte((byte)this.type);
            ms.mType = ((MsgType)this.type);
            ms.Write(this.id);
            ms.Write(this.position);
            ms.Write(this.yValue);
            ms.Write(this.move);
            ms.Write(this.rotationAim);
            ms.Write(this.fightstate);
            //field name=  type    type=  MsgType     has not auto-gen
        }
            public override void Update()
            {
                base.Update();

                if (_obj is DataMsgCBP)
                {
                    DataMsgCBP dataMsgCBP = (DataMsgCBP)_obj;
                    Clipboard.SetData(dataMsgCBP.format, dataMsgCBP.content);
                }
                else if (_obj is InitFileCBP)
                {
                    ClipboardFiles.RecvClipboardFiles(Server.CommSocket);
                }
                else if (_obj is GetMsgCBP)
                {
                    IDataObject clipboardData = Clipboard.GetDataObject();
                    string[]    formats       = clipboardData.GetFormats();
                    foreach (string format in formats)
                    {
                        if (format == DataFormats.FileDrop)
                        {
                            continue;
                        }
                        Console.WriteLine("Format: " + format);
                        MsgStream.Send(new DataMsgCBP(format, clipboardData.GetData(format)),
                                       Server.CommSocket);
                    }

                    if (Clipboard.ContainsFileDropList())
                    {
                        if (ClipboardFiles.GetCBFilesSize() > ClipboardFiles.MaxSize)
                        {
                            MsgStream.Send(new MaxSizeCBP(), Server.CommSocket);
                            Object response = MsgStream.Receive(Server.CommSocket);
                            if (!(response is ConfirmCBP))
                            {
                                return;
                            }
                        }
                        MsgStream.Send(new InitFileCBP(), Server.CommSocket);
                        ClipboardFiles.SendClipboardFiles(Server.CommSocket);
                        MsgStream.Send(new StopFileCBP(), Server.CommSocket);
                        MsgStream.Receive(Server.CommSocket); // wait for an ack
                    }
                    else
                    {
                        MsgStream.Send(new StopFileCBP(), Server.CommSocket);
                    }
                }
            }
    public void SendPingMsg(int ping)
    {
        var msg = MsgStream.Create(MsgType.CUSTOM_CMD, CustomMsgType.ping);

        msg.Write(mPing);
        mLastPingTime = DateTime.Now;
        //    mLastPingTimes.Add(DateTime.Now);
        this.AddSendMsg(msg);
        // if (pingMsgNum >= 2)
        {
            //已经发送过了 但是服务器未响应 认为断开连接了
        }
        ++pingMsgNum;
        //  this.LastSendPingTimestamp = Utils.GetTimestampSecondsInt();
    }
Exemple #12
0
 public override void Update()
 {
     try
     {
         _obj = null;
         _obj = MsgStream.Receive(Server._commSocket);
         if (_obj == null)
         {
             Server.State = new WaitingState();
         }
     }
     catch (SocketException)
     {
     }
 }
Exemple #13
0
            public override void Update()
            {
                base.Update();

                if (_obj is AuthMsg)
                {
                    // authentication
                    AuthMsg authMsg = (AuthMsg)_obj;
                    if (authMsg.psw == Server._password)
                    {
                        MsgStream.Send(new AckMsg(true), Server._commSocket);
                        Server.SetAuthenticated();
                    }
                    else
                    {
                        MsgStream.Send(new AckMsg(false), Server._commSocket);
                        Server.State = new WaitingState();
                    }
                }
            }
        /////////////-----------dont modify follow code your modifications will be loss
        /////////////-----------dont modify follow code your modifications will be loss
        /////////////-----------dont modify follow code your modifications will be loss
        /////////////-----------dont modify follow code your modifications will be loss
        /////////////-----------dont modify follow code your modifications will be loss
        /////////////-----------dont modify follow code your modifications will be loss



        //---Auto Generate Code Start---
        //把该类的field 写入到stream中
        public void Encode(MsgStream ms)
        {
            ms.stream.WriteByte((byte)this.type);
            ms.mType = ((MsgType)this.type);
            ms.Write(this.xxx);
            ms.Write((short)this.list.Count);
            int ____COUNT___list = list.Count;

            for (int i = 0; i < ____COUNT___list; i++)
            {
                ms.Write(this.list[i]);
            }
            ;
            ms.Write((short)this.lis1111t.Count);
            int ____COUNT___lis1111t = lis1111t.Count;

            for (int i = 0; i < ____COUNT___lis1111t; i++)
            {
                ms.Write(this.lis1111t[i]);
            }
            ;
            ms.Write((short)this.lis2312323t.Count);
            int ____COUNT___lis2312323t = lis2312323t.Count;

            for (int i = 0; i < ____COUNT___lis2312323t; i++)
            {
                ms.Write(this.lis2312323t[i]);
            }
            ;
            ms.Write(this.xxxxxx);
            ms.Write(this.plsqsfq);
            ms.Write(this.my_name);
            //field name=  type    type=  MsgType     has not auto-gen
            //field name=  _name    type=  Single     has not auto-gen
            //field name=  kv    type=  Dictionary`2     has not auto-gen
        }
Exemple #15
0
 public AwaitableWrapper WriteMultipleAsyncR(BytesView bv)
 {
     return(new AwaitableWrapper(MsgStream.SendMsg(new Msg(bv))));
 }
Exemple #16
0
 public Task WriteAsync(BytesSegment bs)
 {
     return(MsgStream.SendMsg(new Msg(new BytesView(bs.Bytes, bs.Offset, bs.Len))));
 }
 virtual public void AddSendMsg(MsgStream msg)
 {
     throw new NullReferenceException();
 }
Exemple #18
0
 public async Task Shutdown(SocketShutdown direction)
 {
     await MsgStream.Close(new CloseOpt(CloseType.Shutdown, direction)).CAF();
 }
Exemple #19
0
 public async Task Close()
 {
     await MsgStream.Close(new CloseOpt(CloseType.Close)).CAF();
 }
Exemple #20
0
    private static byte[] _buffer_send    = new byte[4096]; // 4kb buffer cache ,avoid memory-alloc
    private void ThreadFunction_Send()
    {
        MsgStream ms = null;

        try
        {
            _inner_socket.NoDelay = true;
            while (_thread_running && isConnected)
            {
                Thread.Sleep(1);
                if (ms != null)
                {
                    ms.Dispose();
                    ms = null;
                }
                while (_sendQueue.Empty() == false && isConnected && _thread_running)
                {
                    ms = _sendQueue.Dequeue();
                    if (ms == null)
                    {
                        continue;
                    }
                    //减小 缓冲区 异常 的概率
                    //TODO 考虑改为 异步IO
                    bool ok = false;
                    using (ms)
                    {
                        byte[] buffer = null;
                        buffer = ms.stream.buffer;
                        XOREncrypt.Encrypt(buffer, buffer.Length);
                        int len = ms.stream.Length;
                        if (len < MAX_VALID_BUFFER_LEN)
                        {
                            try
                            {
                                byte[] buf = System.BitConverter.GetBytes(len);
                                len = buf.Length + len;
                                buf.CopyTo(_buffer_send, 0);             //write data len

                                buffer.CopyTo(_buffer_send, buf.Length); //write data
                                                                         // Debug.LogError("send cus " + ms.Msg + "len " + send.Length);
                                                                         //    Debug.LogWarning("send buffer len=" + len);
                                int send_len = 0;
                                while (send_len < len)
                                {
                                    int l = _inner_socket.Send(_buffer_send, send_len, len - send_len, SocketFlags.None);
                                    if (l >= 0)
                                    {
                                        send_len += l;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }

                                if (send_len == len)
                                {
                                    ok = true;
                                }
                            }
                            catch (Exception e)
                            {
                                ok = false;
                            }
                        }
                    }
                    ms = null;
                    if (!ok)
                    {
                        Debug.LogError("TcpSocket error send buffer overfollow 0x1  ");
                        this.Disconnected();
                        break;
                    }
                }
            }
            this.Disconnected();
        }
        catch (Exception e)
        {
            Debug.Log(e);
            this.Disconnected();
        }
        if (ms != null)
        {
            ms.Dispose();
            ms = null;
        }
        while (_sendQueue.Empty() == false)
        {
            var x = _sendQueue.Dequeue();
            if (x != null)
            {
                x.Dispose();
            }
        }
        Debug.Log("[NetWork]:Socket Send Thread Close");
    }
Exemple #21
0
    private void ThreadFunction_Recv()
    {
        try
        {
            _inner_socket.NoDelay = true;
            while (_thread_running && isConnected)
            {
                //      Thread.Sleep(1);//能减少socket error 10054 出现的 概率
                byte[] buffer     = _buffer_head;
                int    c          = 0;
                bool   will_break = false;
                while (c < 4)
                {
                    int l = _inner_socket.Receive(buffer, c, 4 - c, SocketFlags.None);  // _inner_tcp_stream.Read(buffer, c, 4 - c);
                    if (l > 0)
                    {
                        c += l;
                    }
                    else if (l == 0)
                    {
                        this.Disconnected();
                        Debug.Log("socket read faild 4 server disconnected");
                        will_break = true;
                        break;
                    }
                    else
                    {
                        this.Disconnected();
                        Debug.Log("socket read faild 1");
                        will_break = true;
                        break;
                    }
                }
                if (will_break)
                {
                    break;
                }
                if (!isConnected || !_thread_running)
                {
                    break;
                }
                int len = (int)System.BitConverter.ToInt32(buffer, 0);
                if (len < MAX_VALID_BUFFER_LEN)
                {
                    //byte[] buf = new byte[len];
                    byte[] buf = Base.MemoryPool.Alloc(len);
                    try
                    {
                        int read_len = 0;
                        while (read_len < len)
                        {
                            int l = _inner_socket.Receive(buf, read_len, len - read_len, SocketFlags.None);// _inner_tcp_stream.Read(buf, read_len, len - read_len);
                            if (l > 0)
                            {
                                read_len += l;
                            }
                            else if (l == 0)
                            {
                                /*
                                 * //https://msdn.microsoft.com/zh-cn/library/8s4y8aff(v=vs.90).aspx
                                 * 如果当前使用的是面向连接的 Socket,那么 Receive 方法将会读取所有可用的数据,直到达到缓冲区的大小为止。如果远程主机使用 Shutdown 方法关闭了 Socket 连接,并且所有可用数据均已收到,则 Receive 方法将立即完成并返回零字节。*/
                                break;
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (read_len != len)
                        {
                            this.Disconnected();
                            Debug.Log("socket read faild 2");
                            break;
                        }
                        XOREncrypt.Decrypt(buf, len);
                        byte by = buf[0];
                        if (by == 1) // 占位符
                        {
                            MsgStream msg = MsgStream.Create(buf, len);

                            if (msg.IsCustomCmd)
                            {
                                if (msg.CustomType == CustomMsgType.ping)
                                {
                                    TimeSpan ts = DateTime.Now - mLastPingTime;//mLastPingTimes[idx];
                                    mPing         = (int)(ts.TotalMilliseconds);
                                    mLastPingTime = DateTime.Now;
                                    //    this.LastSendPingTimestamp = Utils.GetTimestampSecondsInt();
                                    msg.Dispose();
                                    continue;
                                }
                            }
                            _recvQueue.Enqueue(msg);
                        }
                        else
                        {
                            //maybe dicconnected by server or net error
                            Debug.LogError("****************** unexp bytes headdrer=" + (int)by + " len=" + len + " read_len=" + read_len);
                            this.Disconnected();
                        }
                    }
                    catch (Exception e)
                    {
                        //不回收  让他GC掉好了
                    }
                }
                else
                {
                    this.Disconnected();
                    Debug.LogError("TcpSocket error send buffer overfollow 0x2  ");
                }
            }
        }
        catch (SocketException e)
        {
            Debug.Log("TcpSocket:" + e.Message + "   " + e.ErrorCode + "  " + e.NativeErrorCode + "  " + e.SocketErrorCode);
        }
        catch (Exception e)
        {
            Debug.Log("TcpSocket:" + e.Message);
        }
        this.Disconnected();
        while (_recvQueue.Empty() == false)
        {
            var x = _recvQueue.Dequeue();
            if (x != null)
            {
                x.Dispose();
            }
        }
        Debug.Log("[NetWork]:Socket Recv Thread Close");
    }
 //会在Decode调用之后才会调用
 public void CustomDecode(MsgStream ms)
 {
 }
        //------------end of your own field

        //////////////////add your own  method in here



        //////////////////end of your method field

        //if you want to encode custom member or unsuport member please write your code here
        //会在Encode之后才调用
        public void CustomEncode(MsgStream ms)
        {
        }
Exemple #24
0
        public void SendMsg()
        {
            Message m;
            int     i = 0;

            while (true)
            {
                while (_ee.WaitOne())
                {
                    lock (_eq)
                    {
                        while (true)
                        {
                            try
                            {
                                m = _eq.Dequeue();
                                _eqToSend.Enqueue(m);
                                i++;
                            }
                            catch (InvalidOperationException)
                            {
                                break;
                            }
                        }
                    }

                    while (i != 0)
                    {
                        m = _eqToSend.Dequeue();
                        i--;

                        /* checking type */

                        if ((m is StopComm) && (_eas == ((StopComm)m).i))
                        {
                            continue;
                        }

                        if (m is InitComm)
                        {
                            if (_eas != -1)
                            {
                                if (_es[_eas] == null)
                                {
                                    _eas = -1;
                                }
                                else
                                {
                                    continue;
                                }
                            }

                            _eas = ((InitComm)m).i; // changing active socket
                        }

                        if ((_eas != -1) && (_es[_eas] != null))
                        {
                            try
                            {
                                MsgStream.Send(m, _es[_eas]); //sending data
                                //Console.WriteLine("Sent");
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("Error during event comunication: " + e.Message);
                                System.Windows.Forms.MessageBox.Show("Ops...\nSomething goes wrong during Events Transfer.\nThe connection will be closed.\nTry again later.",
                                                                     "Event Transfer Error!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                                _sp[_eas].DisconnectionReq();
                                _eas = -1;
                                continue;
                            }

                            if (m is InitComm)
                            {
                                _sp[_eas].Activation();
                                continue;
                            }

                            if (m is StopComm)
                            {
                                //Console.WriteLine("StopComm Msg Processed Well");
                                _sp[_eas].Deactivation();
                                _eas = -1;  // no active socket from now till a new InitComm Message
                            }
                        }
                    } //end sending loop
                }     //end wait on event
            }         //end infinite loop
        }             //end SendMsg
Exemple #25
0
        public void ReceiveCBMsg()
        {
            Message m;
            int     i = 0;

            while (true)
            {
                while (_de.WaitOne())
                {
                    lock (_dq) { m = _dq.Dequeue(); }
                    i = ((GetMsgCBP)m).i;

                    //Console.WriteLine("Processing Getting RQ to: " + i);

                    if ((i != 0) && (i != 1) && (i != 2) && (i != 3))
                    {
                        continue;
                    }

                    if (_ds[i] != null)
                    {
                        _sp[i].CBGetting();

                        try
                        {
                            MsgStream.Send(m, _ds[i]);
                            //Console.WriteLine("richiesta di ricezione inviata");

                            do
                            {
                                m = (Message)MsgStream.Receive(_ds[i]);

                                if (m is DataMsgCBP)
                                {
                                    DataMsgCBP dataMsgCBP = (DataMsgCBP)m;
                                    //Console.WriteLine("ricevuto pacchetto: " + dataMsgCBP.format);
                                    System.Windows.Forms.Clipboard.SetData(dataMsgCBP.format, dataMsgCBP.content);
                                }


                                if (m is InitFileCBP) //FILEMSG
                                {
                                    /*
                                     * System.Windows.Forms.MessageBox.Show("Receiving file/s from server: " + i.ToString()
                                     + " .\nYou will be advised when the transfer is completed.", "Starting File/s Transfer",
                                     +  System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                                     */

                                    ClipboardFiles.RecvClipboardFiles(_ds[i]);
                                    Console.WriteLine("CBP : Received Files.");

                                    /*
                                     *
                                     * System.Windows.Forms.MessageBox.Show("File/s received from server: " + i.ToString()
                                     + " .", "Transfer completed",
                                     +  System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                                     */
                                    _sp[i].EnableCB();
                                    break;
                                }

                                if (m is MaxSizeCBP)
                                {
                                    if (System.Windows.Forms.MessageBox.Show("The size of clipboard's content is greater than MaxSize: " + ClipboardFiles.MaxSize
                                                                             + " \nConfirm the transfer?", "File size exceeding", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                                    {
                                        System.Windows.Forms.MessageBox.Show("Receiving file/s from server: " + i.ToString()
                                                                             + " .\nYou will be advised when the transfer is completed.", "Starting File/s Transfer",
                                                                             System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);

                                        MsgStream.Send(new ConfirmCBP(), _ds[i]);
                                        ClipboardFiles.RecvClipboardFiles(_ds[i]);

                                        System.Windows.Forms.MessageBox.Show("File/s received from server: " + i.ToString()
                                                                             + " .", "Transfer completed",
                                                                             System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);

                                        _sp[i].EnableCB();
                                        break;
                                    }
                                    else
                                    {
                                        MsgStream.Send(new StopFileCBP(), _ds[i]);
                                        _sp[i].EnableCB();
                                        break;
                                    }
                                }
                            }while(!(m is StopFileCBP));

                            _sp[i].EnableCB();
                        }
                        catch (Exception e)
                        {
                            //Console.WriteLine("Errore nella richiesta CB: chiusura sockets e disconnessione.");
                            System.Windows.Forms.MessageBox.Show("Ops...\nSomething goes wrong during Clipboard Transfer[on Receiving].\nThe connection will be closed.\nTry again later.",
                                                                 "Clipboard Transfer Error!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                            _sp[i].DisconnectionReq();
                            Console.WriteLine("Clipboard file transfer error: " + e.Message);
                        }
                    } //end checking socket nullity
                }     //end wait condition
            }         //end infinite loop
        }             //end ReceiveCBMsg