当前位置: 首页>>代码示例>>C#>>正文


C# Socket.Receive方法代码示例

本文整理汇总了C#中Socket.Receive方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.Receive方法的具体用法?C# Socket.Receive怎么用?C# Socket.Receive使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Socket的用法示例。


在下文中一共展示了Socket.Receive方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: EchoRequestHandler

	static byte [] EchoRequestHandler (Socket socket)
	{
		MemoryStream ms = new MemoryStream ();
		byte [] buffer = new byte [4096];
		int bytesReceived = socket.Receive (buffer);
		while (bytesReceived > 0) {
			ms.Write (buffer, 0, bytesReceived);
			if (socket.Available > 0) {
				bytesReceived = socket.Receive (buffer);
			} else {
				bytesReceived = 0;
			}
		}
		ms.Flush ();
		ms.Position = 0;

		string request = string.Empty;
		using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
			request = sr.ReadToEnd ();
		}

		StringWriter sw = new StringWriter ();
		sw.WriteLine ("HTTP/1.1 200 OK");
		sw.WriteLine ("Content-Type: text/xml");
		sw.WriteLine ("Content-Length: " + request.Length.ToString (CultureInfo.InvariantCulture));
		sw.WriteLine ();
		sw.Write (request);
		sw.Flush ();

		return Encoding.UTF8.GetBytes (sw.ToString ());
	}
开发者ID:mono,项目名称:gert,代码行数:31,代码来源:test.cs

示例2: Main

    public static void Main(string[] args)
    {
        if(args.Length!=1)
        {
            usage();
            return;
        }

        try
        {
            string hostname=args[0];

            IPHostEntry IPHost=Dns.Resolve(hostname);
            Console.WriteLine(IPHost.HostName);
            string []aliases=IPHost.Aliases;

            IPAddress[] addr=IPHost.AddressList;
            Console.WriteLine(addr[0]);
            EndPoint cp=new IPEndPoint(addr[0],80);

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

            sock.Connect(cp);

            if(sock.Connected)
            {
                Console.WriteLine("OK");
            }

            Encoding ASCII=Encoding.ASCII;
            string Get="GET/HTTP/1.1\r\nHost:"+hostname+"\r\nConnection:Close\r\n\r\n";
            Byte[] ByteGet=ASCII.GetBytes(Get);
            Byte[] RecvBytes=new Byte[256];

            sock.Send(ByteGet,ByteGet.Length,0);

            Int32 bytes=sock.Receive(RecvBytes,RecvBytes.Length,0);
            Console.WriteLine(bytes);
            String strRetPage=null;
            strRetPage=strRetPage+ASCII.GetString(RecvBytes,0,bytes);
            while(bytes>0)
            {
                bytes=sock.Receive(RecvBytes,RecvBytes.Length,0);
                strRetPage=strRetPage+ASCII.GetString(RecvBytes,0,bytes);
                Console.WriteLine(strRetPage);
            }

            sock.Shutdown(SocketShutdown.Both);
            sock.Close();
        }
        catch(Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
开发者ID:ShiJess,项目名称:CompanyStudy,代码行数:55,代码来源:GetDefaultPage.cs

示例3: PumpMessageReader

    public int PumpMessageReader(ref Socket t_sock, ref BinaryMessage t_msg)
    {
        int messageRead = -1;

        if (AmountBuffered() > 0)
        {
            ushort t_len = BitConverter.ToUInt16(m_buffer, m_startPos);
            if (AmountBuffered() > t_len)
            {
                byte[] t_msgBuff = new byte[t_len];
                Get(ref t_msgBuff);
                t_msg.AddToMessage(ref t_msgBuff, t_len);
                messageRead = 1;

                return messageRead;
            }
        }
        if (t_sock.Available > 0)
        {
            //Debug.Log("Im inside!");
            byte[] t_buffer = new byte[1024];
            int recvdBytes = t_sock.Receive(t_buffer);
            Put(ref t_buffer, recvdBytes);

            messageRead = 2;
            return messageRead;
        }
        return messageRead;
    }
开发者ID:RanBlade,项目名称:Portfolio,代码行数:29,代码来源:BufferedReader.cs

示例4: run

        public void run()
        {
            running = true;
            try
            {
                Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("192.168.0.14");
                System.Net.IPEndPoint remoteEP = new IPEndPoint(ipAdd, 1234);
                soc.Connect(remoteEP);
                soc.Send(System.Text.Encoding.ASCII.GetBytes("Output\n"));
                while (running)
                {
                    byte[] buffer = new byte[1024];
                    int iRx = soc.Receive(buffer);
                    char[] chars = new char[iRx];

                    System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
                    int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
                    System.String recv = new System.String(chars);
                    //Console.WriteLine(recv);
                    Debug.Log(recv);
                }
                soc.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
开发者ID:James534,项目名称:ServerClient,代码行数:29,代码来源:ListenClient.cs

示例5: Main

 static void Main(string[] args)
 {
     //设定服务器IP地址
     IPAddress ip = IPAddress.Parse ("127.0.0.1");
     Socket clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     try {
         clientSocket.Connect (new IPEndPoint (ip, 8885)); //配置服务器IP与端口
         Console.WriteLine ("连接服务器成功");
     } catch {
         Console.WriteLine ("连接服务器失败,请按回车键退出!");
         return;
     }
     //通过clientSocket接收数据
     int receiveLength = clientSocket.Receive (result);
     Console.WriteLine ("接收服务器消息:{0}", Encoding.ASCII.GetString (result, 0, receiveLength));
     //通过 clientSocket 发送数据
     for (int i = 0; i < 10; i++) {
         try {
             Thread.Sleep (1000);    //等待1秒钟
             string sendMessage = "client send Message Hellp" + DateTime.Now;
             clientSocket.Send (Encoding.ASCII.GetBytes (sendMessage));
             Console.WriteLine ("向服务器发送消息:{0}" + sendMessage);
         } catch {
             clientSocket.Shutdown (SocketShutdown.Both);
             clientSocket.Close ();
             break;
         }
     }
     Console.WriteLine ("发送完毕,按回车键退出");
     Console.ReadLine ();
 }
开发者ID:hebbaixue99,项目名称:XJDemoServer,代码行数:31,代码来源:SocketClientDemo.cs

示例6: Update

    // Update is called once per frame
    void Update()
    {
        if (server.Pending())
        {
            //print ("comunica com cliente");
            cliente = server.AcceptSocket();
            cliente.Blocking = false;

            // operacoes de escrita e leitura com cliente
            byte [] mensagem = new byte[1024];
            cliente.Receive (mensagem); //leitura da mensagem enviada pelo cliente
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding ();
            strMessage = encoding.GetString (mensagem).ToString (); // string contendo mensagem recebida do cliente
            //print (strMessage);

            //prepara mensagem para envio
            byte[] envioBuffer = new byte[4];
            envioBuffer[0] = (byte)'a';
            envioBuffer[1] = (byte)'c';
            envioBuffer[2] = (byte)'k';
            envioBuffer[3] = 10;
            cliente.Send(envioBuffer); //envia mensagem ao cliente

        }

        // utiliza a mensagem recebida do cliente que foi armazenada
        // na variavel strMessage para atuar no objeto Cube da cena
        if (strMessage.Contains("noventa")) {
            meuservo.GetComponent<Servo_Motor_Limitado>().rotacao = 90; // rotaciona o servo em 90 graus
        }
    }
开发者ID:ClaudioMota,项目名称:SimuladorRoboUnity,代码行数:32,代码来源:servidor.cs

示例7: Receive

 public static void Receive(Socket socket, byte[] buffer, int offset, int size, int timeout)
 {
     int startTickCount = Environment.TickCount;
       int received = 0;  // how many bytes is already received
       do {
     if (Environment.TickCount > startTickCount + timeout)
       throw new Exception("Timeout.");
     try {
       received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None);
       Debug.Log("recved.");
     }
     catch (SocketException ex)
     {
       if (ex.SocketErrorCode == SocketError.WouldBlock ||
           ex.SocketErrorCode == SocketError.IOPending ||
           ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
       {
         // socket buffer is probably empty, wait and try again
         Thread.Sleep(30);
       }
       else
         throw ex;  // any serious error occurr
     }
       } while (received < size);
 }
开发者ID:hoge-maru,项目名称:janken-net-client,代码行数:25,代码来源:JankenTcp.cs

示例8: InsertObject

    public int InsertObject(byte[] obj, float[] coord)
    {
        int answer = -5;
        BinaryFormatter bf = new BinaryFormatter ();
        MemoryStream ms = new MemoryStream ();
        byte[] instream;

        Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        socket.Connect (new IPEndPoint(IPAddress.Parse("10.9.169.218"), 1234));

        InsertQuery iq = new InsertQuery(new AskObject(coord, 0, 0, obj, 0));

        ms = new MemoryStream();
        bf.Serialize(ms, iq);
        socket.Send(ms.ToArray());

        instream = new byte[100000];
        socket.Receive(instream);
        ms = new MemoryStream (instream);
        object ans = bf.Deserialize (ms);
        if (ans is BoolIntResult) {
            BoolIntResult ans2 = (BoolIntResult)ans;
            if (ans2.boolVal == true)
                answer = ans2.integer;
        } else {
            Debug.Log ("Wrong confirmation packet.");
        }
        socket.Close();
        return answer;
    }
开发者ID:ASchvartzman,项目名称:518Project-ASK,代码行数:30,代码来源:Client.cs

示例9: FetchObjects

    public void FetchObjects(ConcurQueue<int> queue, int[] keys)
    {
        BinaryFormatter bf = new BinaryFormatter ();
        MemoryStream ms = new MemoryStream ();
        byte[] instream = new byte[100000];

        Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        socket.Connect (new IPEndPoint(IPAddress.Parse("10.9.169.218"), 1234));

        FetchQuery fq = new FetchQuery(new float[]{0, 0}, keys);
        bf.Serialize (ms, fq);
        socket.Send (ms.ToArray());

        instream = new byte[100000];
        socket.Receive (instream);
        ms = new MemoryStream (instream);
        object obj2 = bf.Deserialize (ms);

        if (obj2 is ObjectResult) {
            ObjectResult or = (ObjectResult) obj2;
            foreach(AskObject askobject in or.askObjects){
                queue.Enqueue (askobject.objectId);
            }
        } else {
            Debug.Log("Wrong kind of object.");
        }
    }
开发者ID:ASchvartzman,项目名称:518Project-ASK,代码行数:27,代码来源:Client.cs

示例10: Receive

 public static void Receive(Socket client_socket)
 {
     byte[] Rec_bytes = new byte[100];
     int messageLength = client_socket.Receive(Rec_bytes);
     Console.WriteLine("Received...");
     for (int i = 0; i < messageLength; i++)
         Console.Write(Convert.ToChar(Rec_bytes[i]));
 }
开发者ID:ribler,项目名称:CS-Connection,代码行数:8,代码来源:Program.cs

示例11: Receive

 public static void Receive(Socket s)
 {
     byte[] b = new byte[100];
     int k = s.Receive(b);
     Console.WriteLine("Recieved...");
     for (int i = 0; i < k; i++)
         Console.Write(Convert.ToChar(b[i]));
 }
开发者ID:ribler,项目名称:CS-Connection,代码行数:8,代码来源:CSServer.cs

示例12: MakeRequestInternal

    private void MakeRequestInternal(string message)
    {
        // Data buffer for incoming data.
        byte[] bytes = new byte[Transport.PacketSize];

        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            IPAddress ipAddress = IpHelper.ServerIp;
            IPEndPoint remoteEP = new IPEndPoint(ipAddress,port);

            // Create a TCP/IP  socket.
            Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );

            // Connect the socket to the remote endpoint. Catch any errors.
            try
            {
                sender.Connect(remoteEP);

                byte[] msg = Encoding.ASCII.GetBytes(message+Transport.EndFlag);
                // Send the data through the socket.
                int bytesSent = sender.Send(msg);

                // Receive the response from the remote device.
                int bytesRec = sender.Receive(bytes);

                var data = Encoding.ASCII.GetString(bytes,0,bytesRec);
                _clientProtocol.ProcessResponse(data);

                // Release the socket.
                sender.Shutdown(SocketShutdown.Both);
                sender.Close();

            }
            catch (ArgumentNullException ane)
            {
                _clientProtocol.NotifyError();
                Debug.Log(ane.ToString());
            }
            catch (SocketException se)
            {
                _clientProtocol.NotifyError();
                Debug.Log(se.ToString());
            }
            catch (Exception e)
            {
                _clientProtocol.NotifyError();
                Debug.Log(e.ToString());
            }
        }
        catch (Exception e)
        {
            _clientProtocol.NotifyError();
            Debug.Log( e.ToString());
        }
    }
开发者ID:jericho17,项目名称:BallsTestTask,代码行数:57,代码来源:ClientTransport.cs

示例13: Update

    // funcao de atualizacao responsavel por toda a logica de controle e rede
    void Update()
    {
        int tamanho = 0;
        if (server.Pending()){
            cliente = server.AcceptSocket(); //aceita conexao
            cliente.Blocking = false;

            mensagem = new byte[1024];
            tamanho = cliente.Receive (mensagem); //leitura da mensagem enviada pelo cliente
            //System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding ();
            //mensagem = encoding.GetString (mensagem).ToString ();

            byte[] envioBuffer = new byte[4];
            envioBuffer[0] = (byte)'a';
            envioBuffer[1] = (byte)'c';  // mensagem a ser enviada ao cliente
            envioBuffer[2] = (byte)'k';
            envioBuffer[3] = 10;
            cliente.Send(envioBuffer); //envia mensagem ao cliente
        }
        int i;
        for(i=0;i<tamanho;i++){
            switch((char)mensagem[i])
            {
                case 'C': //cima
                    servo2.rotacao-=1;
                break;
                case 'B': //baixo
                    servo2.rotacao+=1;
                break;
                case 'E': //esquerda
                    servo1.rotacao-=1;
                break;
                case 'D': //direita
                    servo1.rotacao+=1;
                break;
                case 'Y': // segue a frente
                    servo5.rotacao-=1;
                break;
                case 'T': // vai para traz
                    servo5.rotacao+=1;
                break;
                case 'A': // abre
                    servo3.rotacao+=1;
                    servo4.rotacao-=1;
                break;
                case 'F': //fecha
                    servo3.rotacao-=1;
                    servo4.rotacao+=1;
                break;
            }
        }
    }
开发者ID:ClaudioMota,项目名称:SimuladorRoboUnity,代码行数:53,代码来源:ServidorCena12.cs

示例14: receiveMessageFromClient

    public static string receiveMessageFromClient(Socket client_socket)
    {
        byte[] Rec_bytes = new byte[255];
        int messageLength = client_socket.Receive(Rec_bytes);
        char[] messageRecv = new char[messageLength];
        for (int i = 0; i < messageLength; i++)
        {
            messageRecv[i] = Convert.ToChar(Rec_bytes[i]);
        }
        string revcString = new string(messageRecv);

        return revcString;
    }
开发者ID:ribler,项目名称:CS-Connection,代码行数:13,代码来源:Server.cs

示例15: Sock_Relay

 // The socket relay Receive bytes, Send them back
 private static void Sock_Relay(Socket sock1, Socket sock2)
 {
     Byte[] bytes = new Byte[1024];
     while (true)
     {
         try
         {
             int bytesrec = sock1.Receive(bytes);
             sock2.Send(bytes, bytesrec, 0);
         }
         catch (Exception e) { Console.WriteLine("{0}", e); Environment.Exit(0);}
     }
 }
开发者ID:trump0dump,项目名称:helpful,代码行数:14,代码来源:port_redir.cs


注:本文中的Socket.Receive方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。