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


C# Socket.Send方法代码示例

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


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

示例1: FlushWrite

    public bool FlushWrite(ref Socket t_sock)
    {
        //Debug.Log(" FLUSH WRITE:" + AmountBuffered().ToString() + " START -- " + m_startPos.ToString() + "  END  -- " + m_endPos.ToString());
        if (AmountBuffered() > 0)
        {
            int amtBuff = AmountBuffered();
            byte[] sendBuffer = new byte[amtBuff];
            if (m_endPos >= m_startPos)
            {
                Array.Copy(m_buffer, m_startPos, sendBuffer, 0, amtBuff);
                int sent = t_sock.Send(sendBuffer, amtBuff, 0);
                m_startPos = GetNextValidIndex(m_startPos, sent);
                return true;
            }
            else
            {
                int lenToEnd = (m_bufferSize) - m_startPos;
                Array.Copy(m_buffer, m_startPos, sendBuffer, 0, lenToEnd);
                Array.Copy(m_buffer, 0, sendBuffer, lenToEnd, m_endPos);
                int sent = t_sock.Send(sendBuffer, amtBuff, 0);
                m_startPos = GetNextValidIndex(m_startPos, sent);
                return true;

            }

        }//send the buffer....
        return false;
    }
开发者ID:RanBlade,项目名称:Portfolio,代码行数:28,代码来源:BufferedWriter.cs

示例2: Send

    public static void Send(Socket socket, byte[] buffer, int offset, int size, int timeout)
    {
        int startTickCount = Environment.TickCount;
          int sent = 0;  // how many bytes is already sent
        Debug.Log("send:"+startTickCount);
          do {
        if (Environment.TickCount > startTickCount + timeout){
            Debug.Log("time out");
          	throw new Exception("Timeout.");
        }
        try {
            Debug.Log("send sock");
          sent += socket.Send(buffer, offset + sent, size - sent, SocketFlags.None);
        }
        catch (SocketException ex)
        {

          if (ex.SocketErrorCode == SocketError.WouldBlock ||
              ex.SocketErrorCode == SocketError.IOPending ||
              ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
          {
            // socket buffer is probably full, wait and try again
                    Debug.Log("sleep");
            Thread.Sleep(30);
          }
          else
            throw ex;  // any serious error occurr
        }
          } while (sent < size);
    }
开发者ID:hoge-maru,项目名称:janken-net-client,代码行数:30,代码来源:JankenTcp.cs

示例3: 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

示例4: 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

示例5: Append

        static void Append(Socket sock, string root)
        {
            var name = sock.Recv(Encoding.UTF8);
            var fileName = Path.GetFileName(name) ?? "";
            var combine = Path.Combine(root, fileName);

            var s = new FileTapeStream(combine);
            Console.WriteLine("Append {0}", fileName);
            long result = 0;
            while (true)
            {
                var verDat = sock.Recv();
                if ((null == verDat) || (verDat.Length == 0))
                    break;

                var version = BitConverter.ToInt64(verDat, 0);
                var data = sock.Recv();

                var cond = TapeAppendCondition.VersionIs(version);
                result = s.TryAppend(data, cond);
                if (result != 0)
                    Console.WriteLine("  " + result);
            }
            s.UpdateCounter(result);
            sock.Send(BitConverter.GetBytes(result));
        }
开发者ID:kstreet,项目名称:lokad-synapse,代码行数:26,代码来源:Program.cs

示例6: RecepcionHandShake

 void RecepcionHandShake(Socket socket, IOMultiPlex revents)
 {
     var idcliente = socket.Recv();
     socket.Send(nombreServidor);
     MethodInvoker action=delegate { listanodos.Items.Add(Encoding.Unicode.GetString(idcliente));};
     listanodos.BeginInvoke(action);
 }
开发者ID:majimenezp,项目名称:EjemplosZeroMQ,代码行数:7,代码来源:Form1.cs

示例7: sendMessage

 public static void sendMessage(Socket clientSocket)
 {
     ASCIIEncoding asn = new ASCIIEncoding();
     String sendString = Console.ReadLine();
     //String sendString = "This is a test!!!!!!!!!!!!!!!!!!!!!!!!";
     clientSocket.Send(asn.GetBytes(sendString));
 }
开发者ID:ribler,项目名称:CS-Connection,代码行数:7,代码来源:Program.cs

示例8: 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

示例9: ConnectServer

    private void ConnectServer(object _thread)
    {
        Thread thread = (Thread)_thread;

        try
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ipString), 25565);

            socket.Connect(ip);

            if (socket.Connected)
            {
                // Start a thread for receiveing player data
                receiveThread = new Thread(ReceiveData);
                receiveThread.IsBackground = true;
                receiveThread.Start();

                // Send a packet containg the player his name
                List<byte> packet = new List<byte>();
                packet.AddRange(BitConverter.GetBytes((ushort)game.playerName.Length));
                packet.AddRange(Encoding.ASCII.GetBytes(game.playerName));
                socket.Send(packet.ToArray(), SocketFlags.None);
            }
        }
        catch (Exception e)
        {
            Debug.LogError("Could not connect.. :: " + e);
        }
        thread.Abort();
    }
开发者ID:Wiebrendh,项目名称:MMORPG,代码行数:31,代码来源:ClientSocket.cs

示例10: 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

示例11: 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

示例12: echoMessage

 public static int echoMessage(Socket clientSocket)
 {
     string messageToSend = testReceive(clientSocket);
     ASCIIEncoding asn = new ASCIIEncoding();
     clientSocket.Send(asn.GetBytes(messageToSend));
     return messageToSend.Length;
 }
开发者ID:ribler,项目名称:CS-Connection,代码行数:7,代码来源:Program.cs

示例13: ReceiverPollInHandler

 private static void ReceiverPollInHandler(Socket receiver, Socket sender)
 {
     var ms = receiver.Recv(Encoding.UTF8);
       var timeout = TimeSpan.FromTicks(int.Parse(ms) * 10000L);
       Console.WriteLine(ms);
       Thread.Sleep(timeout);
       sender.Send(string.Empty, Encoding.UTF8);
 }
开发者ID:nivertech,项目名称:zguide,代码行数:8,代码来源:taskwork2.cs

示例14: Start

	// Use this for initialization
	void Start () {
		socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		IPEndPoint ipe = new IPEndPoint (IPAddress.Parse ("192.168.1.102"), 5113);
		socket.Connect (ipe);
		command=0;
		socket.Send (new byte[]{command});

	}
开发者ID:FernandoHo,项目名称:Shirley1.0,代码行数:9,代码来源:NewBehaviourScript.cs

示例15: 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


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