BeginSend() public method

public BeginSend ( IList buffers, SocketFlags socketFlags, AsyncCallback callback, object state ) : IAsyncResult
buffers IList
socketFlags SocketFlags
callback AsyncCallback
state object
return IAsyncResult
Exemplo n.º 1
0
        public void SendMessageToServer(string argCommandString)
        {
            // create a Packet object from the passed data; this packet can be any object type because we use serialization!
            //Dim mPacket As New Dictionary(Of String, String)
            //mPacket.Add("CMD", argCommandString)
            //mPacket.Add("MSG", argMessageString)
            string mPacket = argCommandString;

            // serialize the Packet into a stream of bytes which is suitable for sending with the Socket
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter mSerializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.MemoryStream mSerializerStream = new System.IO.MemoryStream();
            mSerializer.Serialize(mSerializerStream, mPacket);

            // get the serialized Packet bytes
            byte[] mPacketBytes = mSerializerStream.GetBuffer();

            // convert the size into a byte array
            byte[] mSizeBytes = BitConverter.GetBytes(mPacketBytes.Length + 4);

            // create the async state object which we can pass between async methods
            SocketGlobals.AsyncSendState mState = new SocketGlobals.AsyncSendState(cClientSocket);

            // resize the BytesToSend array to fit both the mSizeBytes and the mPacketBytes
            // ERROR: Not supported in C#: ReDimStatement
            Array.Resize(ref mState.BytesToSend, mPacketBytes.Length + mSizeBytes.Length);

            // copy the mSizeBytes and mPacketBytes to the BytesToSend array
            System.Buffer.BlockCopy(mSizeBytes, 0, mState.BytesToSend, 0, mSizeBytes.Length);
            System.Buffer.BlockCopy(mPacketBytes, 0, mState.BytesToSend, mSizeBytes.Length, mPacketBytes.Length);

            cClientSocket.BeginSend(mState.BytesToSend, mState.NextOffset(), mState.NextLength(), SocketFlags.None, new AsyncCallback(MessagePartSent), mState);
        }
Exemplo n.º 2
0
        IWaitableValue <int> IStreamable.Send(byte[] buffer, int offset, int buffer_length)
        {
            /*if (!Socket.Connected)
             * {
             *  _SocketErrorEvent(SocketError.SocketError);
             *  return (0).ToWaitableValue();
             * }*/

            SocketError error;
            var         ar = Socket.BeginSend(buffer, offset, buffer_length, SocketFlags.None, out error, _EndReceiveEmpty, null);

            var safeList = new[] { SocketError.Success, SocketError.IOPending };

            if (!safeList.Any(s => s == error))
            {
                _SocketErrorEvent(error);
            }

            if (ar == null)
            {
                return((0).ToWaitableValue());
            }

            return(System.Threading.Tasks.Task <int> .Factory.FromAsync(ar, _EndSend).ToWaitableValue());
        }
Exemplo n.º 3
0
    private void OnConnect(IAsyncResult ar)
    {
        try {
            clientSocket.EndConnect(ar);
            // here we are connected, so we send login request!
            byte[]  bytesMsg;
            Message loginMsg = new Message(Command.Login, txtName.Text);
            bytesMsg = loginMsg.toByte();

            clientSocket.BeginSend(bytesMsg,
                                   0,
                                   bytesMsg.Length,
                                   SocketFlags.None,
                                   new AsyncCallback(OnSend),
                                   null);
            clientSocket.BeginReceive(byteData,
                                      0,
                                      byteData.Length,
                                      SocketFlags.None,
                                      new AsyncCallback(OnReceive),
                                      null);
        }
        catch (Exception ex) {
            log("Something went wrong during establishing connection:");
            log(ex.Message);
            btnConnect.Sensitive    = true;
            btnDisconnect.Sensitive = false;
            btnMsg.Sensitive        = false;
        }
    }
Exemplo n.º 4
0
 public void Send(string message)
 {
     if (handshaked)
     {
         Frame  f = new Frame(message);
         byte[] b = draft.CreateClientFrameBytes(f);
         socket.BeginSend(b, 0, b.Length, SocketFlags.None, null, socket);
     }
 }
Exemplo n.º 5
0
        public void sendPackage(byte[] _data, Socket socket)
        {
            // DataPackage _data = new DataPackage("First package", 9999, true);
            // DroidMessage _data = new DroidMessage("Hello socket server");
            try
            {
                if (isOnline == true)
                {
                    byte[] data = _data;
                    //_clientSocket.Send(buffer);
                    // socket.Send(_data);

                    socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
                    byte[] _buf = _buffersList.SingleOrDefault(k => k.Key == socket).Value;

                    // socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
                    socket.BeginReceive(_buf, 0, _buf.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
                }
            }
            catch (Exception ex)
            {
                if (OnServerError != null)
                {
                    OnServerError(null, new NotyArgs(ex.Message));
                }
            }
        }
Exemplo n.º 6
0
 public void SendMessage(Socket client, string message)
 {
     byte[] byteMessage = Encoding.ASCII.GetBytes(message);
     client.BeginSend(byteMessage, 0, byteMessage.Length, SocketFlags.None, new AsyncCallback(SendCallBack), client);
     sendDone.WaitOne();
     sendDone.Reset();
 }
Exemplo n.º 7
0
        /// <summary>
        /// 异步发送器
        /// </summary>
        /// <param name="datagram">报文</param>
        /// <returns>返回是否成功</returns>
        public virtual bool Send(string datagram)
        {
            //如果没有连接无法发送报文
            if (!IsConnection)
            {
                CutConnection("服务器未连接");
                return(false);
            }

            try
            {
                //加上后缀
                byte[]       data = encod.ToString(datagram + this.Suffix);
                IAsyncResult iar  = sock.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendDataEnd), sock);
                return(true);
            }
            catch (SocketException ex)
            {
                //服务器断开
                CutConnection(ex.Message);
            }
            catch (ObjectDisposedException ex)
            {
                //服务器断开
                CutConnection(ex.Message);
            }
            catch (Exception ex)
            {
                //服务器断开
                CutConnection(ex.Message);
            }
            return(false);
        }
Exemplo n.º 8
0
        private async Task<String> httpRequest(Byte method, String headerAndBodyRaw, String link)
        {
            Socket youtubeSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Byte[] requbytes = new Byte[8192];
            Int32 recvd = -1;
            String request = "";
            String headerAndBody = ((method == 1) ? "GET /" : "POST /") + link + headerAndBodyRaw.Substring(headerAndBodyRaw.IndexOf("HTTP/1.1") - 1);

            try
            {
                await Task.Factory.FromAsync(youtubeSock.BeginConnect, youtubeSock.EndConnect, "www.youtube.com", 80, null);

                if (youtubeSock.Connected)
                {
                    var buffer = Encoding.ASCII.GetBytes(headerAndBodyRaw);
                    int bytessent = await Task.Factory.FromAsync<int>(youtubeSock.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, null, youtubeSock), youtubeSock.EndSend);

                    if (await waitForDataToBecomeAvailable(2000, youtubeSock))
                    {
                        recvd = youtubeSock.Receive(requbytes);
                        request = Encoding.ASCII.GetString(requbytes).Substring(0, recvd);
                    }

                    youtubeSock.Dispose();
                }

                return request;
            }
            catch (Exception err)
            {
                LogError("\nhttpRequest() - Error: " + err.Message + "\n\n" + err.StackTrace + "\n" + headerAndBodyRaw);
            }

            return "";
        }
Exemplo n.º 9
0
 /// <summary>
 /// 异步发送信息
 /// </summary>
 public void Send(int cmd, byte[] dataMsg)
 {
     if (_connectState == NetworkClientState.Closed)
     {
         Debug.LogError(cmd + "send error,connectState Closed");
         return;
     }
     try
     {
         _msgCounter++;
         Debug.Log("<color=#00CA66FF>Send:" + cmd + "</color>");
         ByteArray ba = new ByteArray();
         if (dataMsg != null)
         {
             ba.Write(dataMsg.Length + 8);
             ba.Write(cmd);
             ba.Write(_msgCounter);
             ba.Write(dataMsg);
         }
         else
         {
             ba.Write(8);
             ba.Write(cmd);
             ba.Write(_msgCounter);
         }
         byte[] data = ba.GetByteArray();
         ba.Destroy();
         _socket.BeginSend(data, 0, data.Length, 0, DoSend, _socket);
     }
     catch (SocketException ex)
     {
         DoSendError(ex);
     }
 }
Exemplo n.º 10
0
        private static IEnumerator<IAsyncCall> Echo(Socket client)
        {
            byte[] buffer = new byte[1024];
            AsyncCall<int> call = new AsyncCall<int>();

            while (true)
            {
                yield return call
                    .WaitOn(cb => client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, cb, null))
                    & client.EndReceive;

                int bytes = call.Result;
                if (bytes > 0)
                {
                    Console.WriteLine("read {0} bytes from {1}", bytes, client.RemoteEndPoint);

                    yield return call
                        .WaitOn(cb => client.BeginSend(buffer, 0, bytes, SocketFlags.None, cb, null))
                        & client.EndReceive;

                    Console.WriteLine("sent {0} bytes to {1}", bytes, client.RemoteEndPoint);
                }
                else
                {
                    break;
                }
            }

            Console.WriteLine("closing client socket {0}", client.RemoteEndPoint);

            client.Close();
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect("localhost", 4530);

            //实现接受消息的方法
            var buffer = new byte[1024];//设置一个缓冲区,用来保存数据
            //socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback((ar) => 
            //{
            //    var length = socket.EndReceive(ar);
            //    var message = Encoding.Unicode.GetString(buffer, 0, length);
            //    //显示读出来的消息
            //    Console.WriteLine(message);
            //}), null);

            Console.WriteLine("Client connec to the server");
            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
            //接受用户输入,将消息发送给服务器端
            while (true)
            {
                var message = "message from client: " + Console.ReadLine();
                var outputBuffer = Encoding.Unicode.GetBytes(message);
                socket.BeginSend(outputBuffer, 0, outputBuffer.Length, SocketFlags.None, null, null);
            }
            Console.Read();
        }
Exemplo n.º 12
0
 public void BeginSend(Socket objSocket, byte[] data)
 {
     if (objSocket != null && objSocket.Connected)
     {
         objSocket.BeginSend(data, 0, data.Length, SocketFlags.None, this.SendAsynCallBack, objSocket);
     }
 }
Exemplo n.º 13
0
        public void SendAsync(byte[] Data, Action Callback = null)
        {
            var DataCopy = new byte[Data.Length];

            Array.Copy(Data, DataCopy, Data.Length);

            var BuffersCopy = new List <ArraySegment <byte> >()
            {
                new ArraySegment <byte>(DataCopy)
            };

            AsyncQueue.Add(() =>
            {
                try
                {
                    NativeSocket.BeginSend(BuffersCopy, SocketFlags.None, (IAsyncResult) =>
                    {
                        SocketError SocketError;
                        NativeSocket.EndSend(IAsyncResult, out SocketError);
                        Core.EnqueueTask(() =>
                        {
                            if (Callback != null)
                            {
                                Callback();
                            }
                            AsyncQueue.Next();
                        });
                    }, null);
                }
                catch (SocketException SocketException)
                {
                    SocketExceptionThrown(SocketException);
                }
            });
        }
Exemplo n.º 14
0
        private static void BeginSend(Socket socket, byte [] buffer, State state)
        {
            if (socket == null) throw new ArgumentNullException("socket");
            if (buffer == null) throw new ArgumentNullException("buffer");

            if (socket.Connected)
                socket.BeginSend(buffer, 0, buffer.Length, 0, new AsyncCallback(SendCallback), state);
        }
Exemplo n.º 15
0
 public static void Send(Socket handler, String data, Boolean IsOver)
 {
     byte[] byteData = Encoding.UTF8.GetBytes(data);
     StateObject state = new StateObject();
     state.workSocket = handler;
     state.IsOver = IsOver;
     handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), state);
 }
Exemplo n.º 16
0
        private void OnReceiveData(Socket socket)
        {
            string strLogin = "******";
            socket = this.socket;
            byte[] data = Encoding.ASCII.GetBytes(strLogin);

            socket.BeginSend(data, 0, data.Length, SocketFlags.None, sendCallback, socket);
        }
Exemplo n.º 17
0
 public void WriteTo(Socket socket)
 {
     var messageDataLengthBytes = BitConverter.GetBytes(messageData.Length);
     var bytes = new byte[messageDataLengthBytes.Length + messageData.Length];
     Buffer.BlockCopy(messageDataLengthBytes, 0, bytes, 0, messageDataLengthBytes.Length);
     Buffer.BlockCopy(messageData, 0, bytes, messageDataLengthBytes.Length, messageData.Length);
     socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, OnWrite, new	State(socket));
 }
Exemplo n.º 18
0
        private void Send(System.Net.Sockets.Socket client, String data)
        {
            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            // Begin sending the data to the remote device.
            client.BeginSend(byteData, 0, byteData.Length, 0,
                             new AsyncCallback(SendCallback), client);
        }
Exemplo n.º 19
0
        public void Send(System.Net.Sockets.Socket handler, String data)
        {
            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            // Begin sending the data to the remote device.
            handler.BeginSend(byteData, 0, byteData.Length, 0,
                              new AsyncCallback(SendCallback), handler);
        }
Exemplo n.º 20
0
 /**
  * Begins asynchronous writing.
  *
  * @param strData
  *   The data to send.
  */
 public void BeginWrite(string strData)
 {
     byte[] arrData = System.Text.Encoding.ASCII.GetBytes(strData + "\0");
     try {
         penguinSocks.BeginSend(arrData, 0, arrData.Length, Sockets.SocketFlags.None, SendCallback, penguinSocks);
     }catch (System.Exception writeEx) {
         Out.Logger.WriteOutput("Could not send to socket: " + writeEx.Message, Out.Logger.LogLevel.Error);
         disconnectCall();
     }
 }
 public void SendMessage(Socket targetSocket, string messageContent, Action<string> messageSentCallBack)
 {
     byte[] message = BuildMessage(messageContent, Encoding.ASCII);
     if(message.Length>0) {
         var context = new SendContext() {
             TargetSocket = targetSocket, MessageContent = messageContent, MessageSentCallback = messageSentCallBack
         };
         targetSocket.BeginSend(message, 0, message.Length, 0, new AsyncCallback(this.SendCallback), context);
     }
 }
Exemplo n.º 22
0
 public void send_packet(byte[] packet_data, int send_size,Socket socket)
 {
     try
     {
         socket.BeginSend(packet_data, 0, send_size, SocketFlags.None, new AsyncCallback(packet_send), socket_);
     }
     catch (SocketException se)
     {
         MessageBox.Show(se.Message);
     }
 }
Exemplo n.º 23
0
        private IEnumerator<IAsyncCall> SendReceive(string host, int port)
        {
            AsyncCall<IPHostEntry> call = new AsyncCall<IPHostEntry>();

            yield return call
                .WaitOn(cb => Dns.BeginGetHostEntry(host, cb, null)) & Dns.EndGetHostEntry;

            if (!call.Succeeded)
            {
                Console.WriteLine(call.Exception.Message);
                yield break;
            }

            IPAddress addr = call.Result.AddressList[0];

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            AsyncCall call2 = new AsyncCall();
            yield return call2
                .WaitOn(cb => socket.BeginConnect(new IPEndPoint(addr, port), cb, null)) & socket.EndConnect;

            if (!call2.Succeeded)
            {
                Console.WriteLine(call2.Exception.Message);
                yield break;
            }

            byte[] sendBuffer = System.Text.Encoding.ASCII.GetBytes("hello world");
            byte[] receiveBuffer = new byte[1024];
            AsyncCall<int> call3 = new AsyncCall<int>();

            for (int i = 0; i < 128; ++i)
            {
                yield return call3
                    .WaitOn(cb => socket.BeginSend(
                        sendBuffer, 0, sendBuffer.Length, SocketFlags.None, cb, null)) & socket.EndSend;

                int bytesSent = call3.Result;
                Console.WriteLine("{0} sent {1} bytes", socket.LocalEndPoint, bytesSent);

                if (bytesSent > 0)
                {
                    yield return call3
                        .WaitOn(cb => socket.BeginReceive(
                            receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, cb, null)) & socket.EndReceive;

                    Console.WriteLine("{0} read {1} bytes", socket.LocalEndPoint, call3.Result);
                }
            }

            Console.WriteLine("closing socket {0}", socket.LocalEndPoint);

            socket.Close();
        }
Exemplo n.º 24
0
        private IAsyncResult _Send(byte[] buffer, int offset, int buffer_length, AsyncCallback handler, object obj)
        {
            SocketError error;
            var         ar       = Socket.BeginSend(buffer, offset, buffer_length, SocketFlags.None, out error, handler, obj);
            var         safeList = new[] { SocketError.Success, SocketError.IOPending };

            if (!safeList.Any(s => s == error))
            {
                _SocketErrorEvent(error);
            }
            return(ar);
        }
Exemplo n.º 25
0
        /// <summary>
        /// 输出错误状态
        /// </summary>
        /// <param name="state">错误状态</param>
        internal void ResponseError(ResponseState state)
        {
            if (DomainServer != null)
            {
                Response response = DomainServer.GetErrorResponseData(state, Header.IsGZip);
                if (response != null)
                {
                    if (state != ResponseState.NotFound404 || Header.Method != MethodType.GET)
                    {
                        Header.Flag &= HeaderFlag.All ^ HeaderFlag.IsKeepAlive;
                    }
                    if (responseHeader(ref response)) return;
                }
            }
            byte[] data = errorResponseDatas[(int)state];
            System.Net.Sockets.Socket socket = Socket;
            if (data != null && socket != null)
            {
                try
                {
                    SendType = state == ResponseState.NotFound404 && Header.Method == MethodType.GET ? SendType.Next : SendType.Close;
                    Data.Set(data, 0, data.Length);
                    Timeout = Config.GetTimeout(Data.Length);
#if DOTNET2
                    SocketError socketError;
                    IAsyncResult async = socket.BeginSend(data, 0, Data.Length, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                    if (socketError == SocketError.Success)
                    {
                        if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                        return;
                    }
#else
                    sendAsyncLock.EnterSleepFlag();
                    sendAsyncEventArgs.SetBuffer(data, 0, Data.Length);
                    if (socket.SendAsync(sendAsyncEventArgs))
                    {
                        sendAsyncLock.SleepFlag = 0;
                        Http.Header.ReceiveTimeout.Push(this, socket);
                        sendAsyncLock.Exit();
                        return;
                    }
                    sendAsyncLock.ExitSleepFlag();
                    if (onSend()) return;
#endif
                }
                catch (Exception error)
                {
                    Server.RegisterServer.TcpServer.Log.Exception(error, null, LogLevel.Exception | LogLevel.AutoCSer);
                }
            }
            HeaderError();
        }
Exemplo n.º 26
0
        ///// <summary>
        ///// 获取请求表单数据[TRY+1]
        ///// </summary>
        ///// <param name="identity">HTTP操作标识</param>
        ///// <param name="page">WEB 页面</param>
        ///// <param name="type">获取请求表单数据回调类型</param>
        ///// <returns>是否匹配会话标识</returns>
        //internal override bool GetForm(long identity, AutoCSer.WebView.Page page, GetFormType type)
        //{
        //    if (Interlocked.CompareExchange(ref this.Identity, identity + 1, identity) == identity)
        //    {
        //        GetFormPage = page;
        //        GetFormType = type;
        //        tryGetForm();
        //        return true;
        //    }
        //    return false;
        //}
        /// <summary>
        /// 获取请求表单数据
        /// </summary>
        /// <param name="page">WEB 页面</param>
        /// <param name="type">获取请求表单数据回调类型</param>
        internal override void GetForm(AutoCSer.WebView.Page page, GetFormType type)
        {
            ++this.Identity;
            GetFormPage = page;
            GetFormType = type;

            Flag |= SocketFlag.GetForm | SocketFlag.IsLoadForm;
            try
            {
                if (Header.Is100Continue == 0)
                {
                    if (getForm()) return;
                }
                else
                {
                    System.Net.Sockets.Socket socket = Socket;
                    if (socket != null)
                    {
                        SendType = SendType.GetForm;
                        Data.Set(continue100, 0, continue100.Length);
                        Timeout = Config.GetTimeout(Data.Length);
#if DOTNET2
                            SocketError socketError;
                            IAsyncResult async = socket.BeginSend(continue100, 0, Data.Length, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                            if (socketError == SocketError.Success)
                            {
                                if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                                return;
                            }
#else
                        sendAsyncLock.EnterSleepFlag();
                        sendAsyncEventArgs.SetBuffer(continue100, 0, Data.Length);
                        if (socket.SendAsync(sendAsyncEventArgs))
                        {
                            sendAsyncLock.SleepFlag = 0;
                            Http.Header.ReceiveTimeout.Push(this, socket);
                            sendAsyncLock.Exit();
                            return;
                        }
                        sendAsyncLock.ExitSleepFlag();
                        if (sendAsyncEventArgs.SocketError == SocketError.Success && sendAsyncEventArgs.BytesTransferred == Data.Length && getForm()) return;
#endif
                    }
                }
            }
            catch (Exception error)
            {
                Server.RegisterServer.TcpServer.Log.Exception(error, null, LogLevel.Exception | LogLevel.AutoCSer);
            }
            HeaderError();
        }
Exemplo n.º 27
0
        private bool SendAsync(byte[] buffer, int offset, int length)
        {
            bool closing = false;

            lock (this)
            {
                Socket socket = this.m_server;
                if (socket == null)
                {
                    closing = true;
                }
                else
                {
                    try
                    {
                        socket.BeginSend(buffer, offset, length, 0, out SocketError error, (ar) =>
                        {
                            try
                            {
                                socket.EndSend(ar, out error);
                                if (error != SocketError.Success)
                                {
                                    closing = true;
                                }
                            }
                            catch (Exception)
                            {
                                closing = true;
                            }
                            if (closing)
                            {
                                this.Close();
                            }
                        }, null);
                        if (error != SocketError.Success && error != SocketError.IOPending)
                        {
                            closing = true;
                        }
                    }
                    catch (Exception)
                    {
                        closing = true;
                    }
                }
            }
            if (closing)
            {
                this.Close();
            }
            return(!closing);
        }
Exemplo n.º 28
0
        public static void SendFile(string path, string parentDirectory, Socket socketFd, ManualResetEvent handle)
        {
            //send File name
            var filePath = Path.Combine(parentDirectory, Path.GetFileName(path));
            filePath = filePath.Replace('\\', '/');
            var pathBytes = Encoding.ASCII.GetBytes(filePath);

            var pathSizeBytes = BitConverter.GetBytes(pathBytes.Length);

            try
            {
                socketFd.Send(pathSizeBytes, pathSizeBytes.Length, 0);

                socketFd.Send(pathBytes, pathBytes.Length, 0);
            }
            catch (Exception exc)
            {
                MessageBox.Show("Exception:\t\n" + exc.Message);
                var window = (ProjectZip)Application.OpenForms[0];
                window.SetControls(true);
            }

            //send File size
            var file = File.ReadAllBytes(path);

            var fileSizeBytes = BitConverter.GetBytes(file.Length);

            try
            {
                socketFd.Send(fileSizeBytes, fileSizeBytes.Length, 0);
            }
            catch (Exception exc)
            {
                MessageBox.Show("Exception:\t\n" + exc.Message);
                var window = (ProjectZip)Application.OpenForms[0];
                window.SetControls(true);
            }

            //send File
            var fas = new FileAndSize
            {
                SocketFd = socketFd,
                File = file,
                FileSize = file.Length,
                SizeRemaining = file.Length,
                Handle = handle
            };

            socketFd.BeginSend(file, 0, (fas.SizeRemaining < FileAndSize.BUF_SIZE ? fas.SizeRemaining : FileAndSize.BUF_SIZE), 0, SendFileCallback, fas);
        }
Exemplo n.º 29
0
 public void SendMessage(Socket targetSocket, byte[] message, Action<SendResult> messageSentCallback)
 {
     var wrappedMessage = SocketUtils.BuildMessage(message);
     if (wrappedMessage.Length > 0)
     {
         targetSocket.BeginSend(
             wrappedMessage,
             0,
             wrappedMessage.Length,
             SocketFlags.None,
             new AsyncCallback(SendCallback),
             new SendContext(targetSocket, wrappedMessage, messageSentCallback));
     }
 }
Exemplo n.º 30
0
 void StartSend(SendingBuffer sendingBuffer)
 {
     //lock (mSendBufferQueue)
     //{
     try
     {
         mSocket?.BeginSend(sendingBuffer.mBuffer, sendingBuffer.mHasSend, sendingBuffer.mPos1 - sendingBuffer.mHasSend, SocketFlags.None, SendCallback, sendingBuffer);
     }
     catch (Exception e)
     {
         Close();
         Profiler.Log.WriteException(e);
     }
     //}
 }
Exemplo n.º 31
0
        public void Send(Socket socket, Data msg)
        {
            byte[] byteData = Data.Serialize(msg);

            if (byteData.Length == SocketState.BufferSize)
                Console.WriteLine("Won't be able to make difference between end of byte array and end of message.");
            else if (byteData.Length > SocketState.BufferSize)
            {
                Console.WriteLine("Message is too long. It is currently not supported.");
            }
            else
            {
                socket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(this.SendCallback), socket);
            }
        }
Exemplo n.º 32
0
 public void Send(byte[] buffer)
 {
     try
     {
         if (ListenerSocker == null)
         {
             return;
         }
         ListenerSocker.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), this);
     }
     catch (Exception ex)
     {
         Log.Log.GetLog().Error(this, "Send", ex);
     }
 }
Exemplo n.º 33
0
 /// <summary>
 /// Sends a byte array to the socket
 /// </summary>
 /// <param name="byteArray">data to be sent</param>
 /// <exception cref="Exception">Socket not bound or connected</exception>
 public void Write(byte[] byteArray)
 {
     if (!_socket.IsBound && !_socket.Connected)
     {
         throw new Exception("Unable to write. Socket is not bound or connected.");
     }
     try
     {
         _socket.BeginSend(byteArray, 0, byteArray.Length, SocketFlags.None, null, null);
     }
     catch (Exception e)
     {
         throw new Exception("Something went wrong writting on the socket.\n" + e.Message);
     }
 }
Exemplo n.º 34
0
    private void sendDrinks(System.Net.Sockets.Socket client)
    {
        // send drinks to client
        log("Constructing drink string:");
        log(getDrinksForMessage());
        Message drinks = new Message(Command.DescribeDrinks, getDrinksForMessage());

        byte[] bytes = drinks.toByte();
        client.BeginSend(bytes,
                         0,
                         bytes.Length,
                         SocketFlags.None,
                         new AsyncCallback(OnSend),
                         client);
    }
        public void send(byte[] data)
        {
            try
            {
                _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _clientSocket.NoDelay = true;
                IPAddress ipAddress = IPAddress.Parse(ip);
                //Server is listening on port 1000
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1000);

                //Connect to the server
                _clientSocket.Connect(ipEndPoint);
                _clientSocket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
            }
            catch { }
        }
Exemplo n.º 36
0
 public void Send(string Input)
 {
     try {
         byte[] Output = System.Text.ASCIIEncoding.ASCII.GetBytes(Input + "\0");
         if (!ConnectionFired && IPacket.SocketUtils.IsConnected(Sock))
         {
             Sock.BeginSend(Output, 0, Output.Length, 0, new System.AsyncCallback(SendCallback), Sockets.SocketFlags.None);
         }
     }
     catch (System.Exception Exception) {
         IServer.OnDisconnection(this);
         if (Program.Debug)
         {
             Utils.Log.Error("Client Socket [Send][" + Input + "] ", Exception.Message);
         }
     }
 }
Exemplo n.º 37
0
        Task IPeer.Send(byte[] buffer, int offset_i, int buffer_length)
        {
            var task = new Task()
            {
                Buffer = buffer, Offset = offset_i, Count = buffer_length
            };

            try
            {
                _Socket.BeginSend(buffer, offset_i, buffer_length, SocketFlags.None, SendDone, state: task);
            }
            catch (Exception e)
            {
                _Enable = false;
            }
            return(task);
        }
Exemplo n.º 38
0
        /// <summary>
        /// Sends the command to the wifi controller, also has a 100 millisecond delay to ensure commands are not lost
        /// </summary>
        /// <param name="command">The command to control the lights</param>
        public async Task Send(byte[] command)
        {
            //TODO:  USE ASYNC COMMANDS
            // ConnectAsync and SendAsync

            var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            var serverAddr = IPAddress.Parse(Ip);
            var endPoint = new IPEndPoint(serverAddr, Port);
            sock.BeginConnect(endPoint, ConnectCallback, sock);
            ConnectDone.WaitOne();

            sock.BeginSend(command, 0, command.Length, 0, SendCallback, sock);

            SendDone.WaitOne();
            //sock.SendTo(command, endPoint);
            await Task.Delay(100);
        }
Exemplo n.º 39
0
        /// <summary>
        /// Sends the command to the wifi controller, also has a 100 millisecond delay to ensure commands are not lost
        /// </summary>
        /// <param name="command">The command to control the lights</param>
        public async Task Send(byte[] command)
        {
            var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            var serverAddr = IPAddress.Parse(this.ip);

            var endPoint = new IPEndPoint(serverAddr, this.port);

            sock.BeginConnect(endPoint, ConnectCallback, sock);
            connectDone.WaitOne();

            sock.BeginSend(command, 0, command.Length, 0, SendCallback, sock);

            sendDone.WaitOne();
            //sock.SendTo(command, endPoint);

            System.Threading.Thread.Sleep(100);
        }
Exemplo n.º 40
0
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="data">要传递的消息内容[字节数组]</param>
        public void OnSendMessage(byte[] data)
        {
            var stream = new MemoryStream();

            switch (_encoderLengthFieldLength)
            {
            case 1:
                stream.Write(new[] { (byte)data.Length }, 0, 1);
                break;

#if BIG_ENDIANESS
            case 2:
                stream.Write(EndianBitConverter.Big.GetBytes((short)data.Length), 0, 2);
                break;

            case 4:
                stream.Write(EndianBitConverter.Big.GetBytes(data.Length), 0, 4);
                break;

            case 8:
                stream.Write(EndianBitConverter.Big.GetBytes((long)data.Length), 0, 8);
                break;
#else
            case 2:
                stream.Write(BitConverter.GetBytes((short)data.Length), 0, 2);
                break;

            case 4:
                stream.Write(BitConverter.GetBytes(data.Length), 0, 4);
                break;

            case 8:
                stream.Write(BitConverter.GetBytes((long)data.Length), 0, 8);
                break;
#endif

            default:
                throw new Exception("unsupported decoderLengthFieldLength: " + _encoderLengthFieldLength +
                                    " (expected: 1, 2, 3, 4, or 8)");
            }
            stream.Write(data, 0, data.Length);
            var all = stream.ToArray();
            stream.Close();
            _socket.BeginSend(all, 0, all.Length, SocketFlags.None, OnSendMessageComplete, all);
        }
Exemplo n.º 41
0
        public void Write(byte[] data, Action dataSentCallback = null)
        {
            if (data.Length < 1)
            {
                throw new InvalidOperationException("Cannot send 0 bytes");
            }

            if (dataSentCallback != null)
            {
                this.onSentCallback = dataSentCallback;
            }

            Core.EventLoop.Instance.Push(() =>
            {
                nativeSocket.BeginSend(data, 0, data.Length,
                                       Winsock.SocketFlags.None, _static_endSend, this);
            });
        }
Exemplo n.º 42
0
 public static void EncryptPacket(Socket socket, ServerState state, int messageId, int unknown, byte[] plainText)
 {
     byte[] cipherText;
     if (messageId == 20100)
     {
         cipherText = plainText;
     }
     else if (messageId == 20104)
     {
         byte[] nonce = GenericHash.Hash(state.clientState.nonce.Concat(state.clientKey).Concat(state.serverKey.PublicKey).ToArray(), null, 24);
         plainText = state.nonce.Concat(state.sharedKey).Concat(plainText).ToArray();
         cipherText = PublicKeyBox.Create(plainText, nonce, state.serverKey.PrivateKey, state.clientKey);
     }
     else
     {
         // nonce was already incremented in ClientCrypto.DecryptPacket
         cipherText = SecretBox.Create(plainText, state.nonce, state.sharedKey).Skip(16).ToArray();
     }
     byte[] packet = BitConverter.GetBytes(messageId).Reverse().Skip(2).Concat(BitConverter.GetBytes(cipherText.Length).Reverse().Skip(1)).Concat(BitConverter.GetBytes(unknown).Reverse().Skip(2)).Concat(cipherText).ToArray();
     socket.BeginSend(packet, 0, packet.Length, 0, new AsyncCallback(SendCallback), state);
 }
Exemplo n.º 43
0
        public void SendMessage(int type)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(new IPEndPoint(ipAd, port));

            ClientState state = new ClientState();
            state.Client = socket;
            ASCIIEncoding asen = new ASCIIEncoding();
            byte[] data = asen.GetBytes("[" + type + "," + DomainController.getInstance().myAccount.accountId + "]");
            //add prefix to data
            state.DataToSend = new byte[data.Length + 4];
            byte[] prefix = BitConverter.GetBytes(data.Length);
            //copy data size prefix
            Buffer.BlockCopy(prefix, 0, state.DataToSend, 0, prefix.Length);
            //copy the data
            Buffer.BlockCopy(data, 0, state.DataToSend, prefix.Length, data.Length);

            socket.BeginSend(state.DataToSend, 0, state.DataToSend.Length,
              SocketFlags.None, new AsyncCallback(ClientSendCallback), state);
            Thread.Sleep(50);
        }
Exemplo n.º 44
0
		protected virtual void Send(Socket socket, string message)
		{
            if (!(socket.Connected))
            {
                // Tell anyone who's listening that we're not connected anymore
                if (this.RemoteDisconnect != null)
                {
                    this.RemoteDisconnect(socket, EventArgs.Empty);
                }

                this.Log("Failed to send - socket disconnected");

                return;
            }

            byte[] buffer = Encoding.Unicode.GetBytes(message);

            SocketError socketError;
            
            socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, out socketError, this.SendCallback, new SendWrapper(socket, message));

            this.ProcessSocketError(socket, socketError);
		}
Exemplo n.º 45
0
    // TODO: make this stuff dynamic/correct!
    protected virtual void OnBtnMessageClicked(object sender, System.EventArgs e)
    {
        // message stuff
        string message = "Msg from server!";

        byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
        // get correct client!
        Gtk.TreeIter sel = new Gtk.TreeIter();
        TreeModel    tm;

        tvConnections.Selection.GetSelected(out tm, out sel);
        string address = (string)(tm.GetValue(sel, 0));

        System.Net.Sockets.Socket client = (System.Net.Sockets.Socket)clients[0];
        Message msg = new Message(Command.DescribeDrinks, "drink1/drink2/drink3");

        byte[] bytes = msg.toByte();
        client.BeginSend(bytes,
                         0,
                         bytes.Length,
                         SocketFlags.None,
                         new AsyncCallback(OnSend),
                         client);
    }
Exemplo n.º 46
0
        private void Send(Socket client, String data)
        {
            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            // Begin sending the data to the remote device.
            client.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), client);
        }
Exemplo n.º 47
0
 protected override int WriteSingleBuffer(ByteBuffer buffer)
 {
     socket.BeginSend(buffer.Bytes, buffer.Position, buffer.Length, SocketFlags.None, WriteCallback, null);
     return(buffer.Length);
 }
Exemplo n.º 48
0
 System.IAsyncResult Utils.Wrappers.Interfaces.ISocket.BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, System.AsyncCallback callback, object state)
 {
     return(InternalSocket.BeginSend(buffer, offset, size, socketFlags, callback, state));
 }
Exemplo n.º 49
0
        /// <summary>
        /// 发送数据 
        /// </summary>
        /// <param name="handler"></param>
        /// <param name="data"></param>
        private static void Send(Socket handler, object data)
        {
            try
            {
                var sendData = data as DataEntity<ResponseData>;

                List<byte> byteData = new List<byte>();
                if (sendData != null)
                {
                    //byteData.AddRange(sendData.Header.ToByte());
                    //byteData.AddRange(sendData.Body.ToByte());
                    byteData.AddRange(sendData.Body.databuf.ToByte());
                    Console.WriteLine("--------------------应答响应数据【{0}】--------------------", Tool.GetDate());
                    Console.WriteLine("Send Data:{0}", sendData.ToString());
                    Console.WriteLine("-------------------------------------------------------------------------------");

                    _iLog.InfoFormat("-------------------------应答响应数据-------------------------");
                    _iLog.InfoFormat("Send Data:{0}", sendData.ToString());
                    _iLog.InfoFormat("--------------------------------------------------------------");

                    Console.WriteLine("发送数据:把byte转换为16进制:{0}", BitConverter.ToString(byteData.ToArray()));

                    _iLog.InfoFormat("发送数据:把byte转换为16进制:{0}", BitConverter.ToString(byteData.ToArray()));
                }
                else
                {
                    byteData.AddRange(Tool.GetEncoding().GetBytes(data.ToString()));
                }

                //开始发送
                handler.BeginSend(byteData.ToArray(), 0, byteData.Count, 0,
                    new AsyncCallback(SendCallback), handler);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                _iLog.Error(ex);
            }
        }
Exemplo n.º 50
0
 /// <summary>
 /// Send data to remote device.
 /// </summary>
 /// <param name="client"></param>
 /// <param name="byteData"></param>
 public void Send(System.Net.Sockets.Socket client, byte[] byteData)
 {
     client.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,
                      new AsyncCallback(SendCallback), client);
 }
Exemplo n.º 51
0
 void Send(Socket s,byte[] data)
 {
     s.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(send_Callback), s);
 }
Exemplo n.º 52
0
 //Send message to just a spacific client
 public void MsgToClient(string msg, Socket soc)
 {
     byte[] data = Encoding.ASCII.GetBytes(msg);
     soc.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallBack), soc);
 }
Exemplo n.º 53
0
        /// <summary>
        /// Send Data Async
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="data"></param>
        public void SendAsync(Socket socket, byte[] data)
        {
            socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), socket);

            sendDone.WaitOne();
        }
Exemplo n.º 54
0
        /// <summary>
        /// Send Data Async
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="data">Message</param>
        public void SendAsync(Socket socket, String data)
        {
            byte[] byteData = Encoding.Unicode.GetBytes(data + EndOfMessage);

            socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), socket);

            sendDone.WaitOne();
        }
Exemplo n.º 55
0
        public virtual void ReceiveCallback(IAsyncResult ar)
        {
            if (TotalSession >= 10000)
            {
                TotalSession = 0;
            }
            TotalSession++;
            System.Net.Sockets.Socket handler = ConnectSocket;
            var srb = ar.AsyncState as SocketReceiveBack;

            try
            {
                if (handler != null && !handler.Connected) //当近端主动Disconnect时会触发
                {
                    Sktconfig?.DisConnectCallback?.Invoke(this);
                    LogMsg(handler.LocalEndPoint.ToString(), handler.RemoteEndPoint.ToString(), $"disconnect remote {handler.RemoteEndPoint}\r\n");
                    return;
                }
                //最大是设置的msgbuffer的长度,如果发送的数据超过了buffer的长度就分批次接收
                //这里在客户端强制关闭也会进去这个回调,但是执行到EndReceive时会出错
                SocketError se;
                var         rEnd = handler?.EndReceive(ar, out se);

                if (rEnd > 0 && srb != null)
                {
                    var receiveBytes = srb.Buffer.Take(rEnd.Value).ToArray();

                    if (LastSessionTime == DateTime.MinValue)
                    {//websockethttp协议升级
                        #region 分析报文、文本
                        LastSessionTime = DateTime.Now;
                        string receiveText = Encoder.GetString(receiveBytes);
                        //确认客户端发送的是websocket握手协议包,解析出key
                        if (receiveText.IndexOf("Sec-WebSocket-Version:", StringComparison.Ordinal) != -1)
                        {
                            SocketConnectType = SocketConnectType.WebSocket;
                            string[] rawClientHandshakeLines = receiveText.Split(new [] { "\r\n" },
                                                                                 StringSplitOptions.RemoveEmptyEntries);

                            string secwebSocketKey =
                                rawClientHandshakeLines.FirstOrDefault(e => e.Contains("Sec-WebSocket-Key:"));
                            string acceptKey =
                                SocketTool.ComputeWebSocketHandshakeSecurityHash09(
                                    secwebSocketKey?.Substring(secwebSocketKey.IndexOf(":", StringComparison.Ordinal) + 2));
                            var newHandshake = Encoder.GetBytes(SocketTool.ComputeNewHandshake(acceptKey));
                            //返回websocket握手包
                            handler.BeginSend(newHandshake, 0, newHandshake.Length, 0, SendCallback, null);
                            handler.BeginReceive(srb.Buffer, 0, BufferSize, 0, ReceiveCallback, srb);
                            LogMsg(handler.LocalEndPoint.ToString(), handler.RemoteEndPoint.ToString(), $"from remote {handler.RemoteEndPoint} webSocket first session receive data [{receiveText}]\r\n");
                            return;
                        }
                        #endregion
                    }
                    else if (SocketConnectType == SocketConnectType.WebSocket)
                    {//websocket解析明文内容
                        receiveBytes = new DataFrame(receiveBytes).Content;
                    }

                    #region 解析每一个数据包
                    //LogMsg(handler.LocalEndPoint.ToString(), handler.RemoteEndPoint.ToString(), $"current session from remote {handler.RemoteEndPoint} receive data [{ BitConverter.ToString(receiveBytes)}]\r\n");
                    var bytepackage = GetPackage(receiveBytes);
                    int queeCount   = bytepackage.Count;
                    handler.BeginReceive(srb.Buffer, 0, BufferSize, 0, ReceiveCallback, srb);
                    for (int i = 0; i < queeCount; i++)
                    {
                        //下面是正常业务逻辑处理
                        var bytemsg = bytepackage.Dequeue();
                        if (bytemsg.Length == 0)
                        {
                            continue;
                        }
                        LogMsg(handler.LocalEndPoint.ToString(), handler.RemoteEndPoint.ToString(), $"from {handler.RemoteEndPoint} receive [{ BitConverter.ToString(bytemsg)}]\r\n");

                        if (srb.MsgRecevieCallBack != null)
                        {
                            srb.MsgRecevieCallBack(bytemsg, this);
                        }
                        else
                        {
                            Sktconfig?.ReceiveCallback?.Invoke(bytemsg, this);
                        }
                        //else //如果回调是空就原样返回,正常收发可达5000次/s
                        //{
                        //    Send(bytemsg);
                        //}
                    }
                    #endregion
                }
                else //远端主动Disconnect时会到达这里
                {
                    if (handler != null)
                    {
                        Sktconfig?.DisConnectCallback?.Invoke(this);
                        LogMsg(handler.LocalEndPoint.ToString(), handler.RemoteEndPoint.ToString(), $"remote {handler.RemoteEndPoint} has close\r\n");
                    }
                }
                LastSessionTime = DateTime.Now;
            }
            catch (SocketException sktex)
            {
                SocketException(handler, sktex);
            }
            catch (Exception ex)
            {
                Exception(ex);
            }
        }
Exemplo n.º 56
0
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
            bool canWrite = CanWrite; // Prevent race with Dispose.
            if (m_CleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            if (!canWrite)
            {
                throw new InvalidOperationException(SR.GetString(SR.net_readonlystream));
            }
            //
            // parameter validation
            //
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size < 0 || size > buffer.Length - offset)
            {
                throw new ArgumentOutOfRangeException("size");
            }

            Socket chkStreamSocket = m_StreamSocket;
            if (chkStreamSocket == null)
            {
                throw new IOException(SR.GetString(SR.net_io_writefailure, SR.GetString(SR.net_io_connectionclosed)));
            }

            try {
                //
                // call BeginSend on the Socket.
                //
                IAsyncResult asyncResult =
                    chkStreamSocket.BeginSend(
                        buffer,
                        offset,
                        size,
                        SocketFlags.None,
                        callback,
                        state);

                return(asyncResult);
            }
            catch (Exception exception) {
                if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException)
                {
                    throw;
                }

                //
                // some sort of error occured on the socket call,
                // set the SocketException as InnerException and throw
                //
                throw new IOException(SR.GetString(SR.net_io_writefailure, exception.Message), exception);
            }
#if DEBUG
        }
#endif
        }
Exemplo n.º 57
0
        /// <summary>
        /// 数据发送完成后的处理
        /// </summary>
        /// <returns></returns>
        private bool onSend()
#endif
        {
#if DOTNET2
            System.Net.Sockets.Socket socket = (System.Net.Sockets.Socket)async.AsyncState;
            if (socket == Socket)
            {
                SocketError socketError;
                int count = socket.EndSend(async, out socketError);
                if (socketError == SocketError.Success)
                {
#else
        START:
            if (sendAsyncEventArgs.SocketError == SocketError.Success)
            {
                int count = sendAsyncEventArgs.BytesTransferred;
                System.Net.Sockets.Socket socket;
#endif
                    Data.MoveStart(count);
                    if (Data.Length == 0)
                    {
                        SendSizeLessCount = 0;
                        //isShutdown = true;
                        switch (SendType)
                        {
                            case SendType.Next:
                                if (receiveNext()) return true;
                                break;
                            case SendType.Body:
                                switch (HttpResponse.Type)
                                {
                                    case ResponseType.ByteArray:
                                        Data.Array = HttpResponse.Body.Array;
                                        Data.SetFull();
                                        goto SENDDATA;
                                    case ResponseType.SubByteArray:
                                    case ResponseType.SubBuffer:
                                        Data = HttpResponse.Body;
                                    SENDDATA:
#if DOTNET2
                                        if (socket != Socket) return false;
#else
                                    if ((socket = Socket) == null) return false;
#endif
                                        SendType = SendType.Next;
                                        Timeout = Config.GetTimeout(Data.Length);
#if DOTNET2
                                        async = socket.BeginSend(Data.Array, Data.Start, Data.Length, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                                        if (socketError == SocketError.Success)
                                        {
                                            if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                                            return true;
                                        }
                                        break;
#else
                                    sendAsyncLock.EnterSleepFlag();
                                    sendAsyncEventArgs.SetBuffer(Data.Array, Data.Start, Data.Length);
                                    if (socket.SendAsync(sendAsyncEventArgs))
                                    {
                                        sendAsyncLock.SleepFlag = 0;
                                        Http.Header.ReceiveTimeout.Push(this, socket);
                                        sendAsyncLock.Exit();
                                        return true;
                                    }
                                    sendAsyncLock.ExitSleepFlag();
                                    goto START;
#endif
                                    case ResponseType.File:
                                        SendFileStream = new FileStream(HttpResponse.BodyFile.FullName, FileMode.Open, FileAccess.Read, FileShare.Read, Http.Header.BufferPool.Size, FileOptions.SequentialScan);
                                        if (HttpResponse.State == ResponseState.PartialContent206) SendFileStream.Seek(Header.RangeStart, SeekOrigin.Begin);
                                        SendType = SendType.File;
                                        Buffer.ToSubByteArray(ref Data);
                                        Timeout = Config.GetTimeout(ResponseSize);
                                        goto SENDFILE;
                                }
                                break;
                            case SendType.File:
                            SENDFILE:
#if DOTNET2
                                if (socket != Socket) return false;
#else
                            if ((socket = Socket) == null) return false;
#endif
                                Data.Set(Buffer.StartIndex, (int)Math.Min(ResponseSize, Buffer.Length));
                                if (SendFileStream.Read(Data.Array, Data.Start, Data.Length) == Data.Length)
                                {
                                    if ((ResponseSize -= Data.Length) == 0) SendType = SendType.Next;
#if DOTNET2
                                    async = socket.BeginSend(Data.Array, Data.Start, Data.Length, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                                    if (socketError == SocketError.Success)
                                    {
                                        if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                                        return true;
                                    }
#else
                                sendAsyncLock.EnterSleepFlag();
                                sendAsyncEventArgs.SetBuffer(Data.Start, Data.Length);
                                if (socket.SendAsync(sendAsyncEventArgs))
                                {
                                    sendAsyncLock.SleepFlag = 0;
                                    Http.Header.ReceiveTimeout.Push(this, socket);
                                    sendAsyncLock.Exit();
                                    return true;
                                }
                                sendAsyncLock.ExitSleepFlag();
                                goto START;
#endif
                                }
                                break;
                            case SendType.GetForm:
                                if (getForm()) return true;
                                break;
                        }
                    }
                    else if ((count >= TcpServer.Server.MinSocketSize || (count > 0 && SendSizeLessCount++ == 0)) && AutoCSer.Threading.SecondTimer.Now <= Timeout)
                    {
#if DOTNET2
                        if (socket == Socket)
                        {
                            async = socket.BeginSend(Data.Array, Data.Start, Data.Length, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                            if (socketError == SocketError.Success)
                            {
                                if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                                return true;
                            }
                        }
#else
                    if ((socket = Socket) != null)
                    {
                        sendAsyncLock.EnterSleepFlag();
                        sendAsyncEventArgs.SetBuffer(Data.Start, Data.Length);
                        if (socket.SendAsync(sendAsyncEventArgs))
                        {
                            sendAsyncLock.SleepFlag = 0;
                            Http.Header.ReceiveTimeout.Push(this, socket);
                            sendAsyncLock.Exit();
                            return true;
                        }
                        sendAsyncLock.ExitSleepFlag();
                        goto START;
                    }
#endif
                    }
#if DOTNET2
                }
#endif
            }
            return false;
        }
Exemplo n.º 58
0
 protected override IAsyncResult Begin(System.Net.Sockets.Socket socket, ByteBuffer[] bufs, AsyncCallback callback, object state)
 {
     return(socket.BeginSend(ByteBuffersToList(bufs), System.Net.Sockets.SocketFlags.None, callback, state));
 }
Exemplo n.º 59
0
        static void Main(string[] args)
        {
            Console.Write("Enter your name:");
            string name = Console.ReadLine();
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                ProtocolType.Tcp);

            client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080));
            Console.WriteLine("Connected to server,enter $q to quit");
            name = "{<" + name.Trim() +">}";
            byte[] nameBuf = Encoding.UTF8.GetBytes(name);
            client.BeginSend(nameBuf, 0, nameBuf.Length, SocketFlags.None, null, null);
            client.BeginReceive(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(Receive), client);
            while (true)
            {
                string msg = Console.ReadLine();
                if (msg == "$q")
                {
                    client.Close();
                    break;
                }

                byte[] output = Encoding.UTF8.GetBytes(msg);
                client.BeginSend(output, 0, output.Length, SocketFlags.None, null, null);
            }
            Console.Write("Disconnected . Press any key to exit...");
            Console.ReadKey();
        }
Exemplo n.º 60
-1
		public void BeginSendNotConnected ()
		{
			Socket sock = new Socket (AddressFamily.InterNetwork,
						  SocketType.Stream,
						  ProtocolType.Tcp);
			
			byte[] send_bytes = new byte[] {10, 11, 12, 13};
			
			try {
				sock.BeginSend (send_bytes, 0,
						send_bytes.Length,
						SocketFlags.None, BSCallback,
						sock);
				Assert.Fail ("BeginSendNotConnected #1");
			} catch (SocketException ex) {
				Assert.AreEqual (10057, ex.ErrorCode, "BeginSendNotConnected #2");
			} catch {
				Assert.Fail ("BeginSendNotConnected #3");
			} finally {
				sock.Close ();
			}
		}