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


C# Socket.Send方法代码示例

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


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

示例1: Main

        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();
        }
开发者ID:qychen,项目名称:AprvSys,代码行数:25,代码来源:ClientCode.cs

示例2: put

 public bool put(string value)
 {
     try
     {
         IPHostEntry hostEntry = Dns.GetHostEntry("");
         IPAddress hostAddress = hostEntry.AddressList[0];
         IPEndPoint remoteEndPoint = new IPEndPoint(hostAddress, 80);
         using (var connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
         {
             connection.Connect(remoteEndPoint);
             connection.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
             connection.SendTimeout = 5000;
             const string CRLF = "\r\n";
             byte[] buffer = Encoding.UTF8.GetBytes(value);
             var requestLine = "PUT /v2/feeds/" + "" + ".csv HTTP/1.1" + CRLF;
             byte[] requestLineBuffer = Encoding.UTF8.GetBytes(requestLine);
             var headers = "Host: " + "" + CRLF + "X-PachubeAPIKey: " + "" + CRLF + "Content-Type: text/csv" + CRLF + "Content-Length: " + buffer.Length + CRLF + CRLF;
             byte[] headerBuffer = Encoding.UTF8.GetBytes(headers);
             connection.Send(requestLineBuffer);
             connection.Send(headerBuffer);
             connection.Send(buffer);
         }
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
开发者ID:Osceus,项目名称:Kinect,代码行数:29,代码来源:PachubeSocket.cs

示例3: StartMirametrixStream

        // 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;
        }
开发者ID:Jeuro,项目名称:inte13s-eye-tracking,代码行数:29,代码来源:EyetrackCommunicator.cs

示例4: TestMetadataServicesComunication

        public void TestMetadataServicesComunication()
        {
            string Host = "127.0.0.1";
            int Port = 2107;
            Socket _clientSocket;

            byte[] _response = new byte[2048];

            IPHostEntry ipHostInfo = Dns.GetHostEntry(Host);//"achilles.cse.tamu.edu");
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, Port);
            _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _clientSocket.Connect(Host, Port);

            Console.WriteLine("Client socket with host ({0}) connected? {1}.", Host, _clientSocket.Connected);

            _clientSocket.Send(Encoding.ASCII.GetBytes("content-length:26\r\nuid:1\r\n\r\n<init_connection_request/>"));

            //_clientSocket.Receive(_response);
            //Console.WriteLine(_response.ToString());

            _clientSocket.Send(Encoding.ASCII.GetBytes("content-length:70\r\nuid:1\r\n\r\n<metadata_request url=\"http://www.amazon.com/gp/product/B0050SYS5A/\"/>"));

            //_clientSocket.Receive(_response);
            //Console.WriteLine(_response.ToString());
        }
开发者ID:ecologylab,项目名称:BigSemanticsCSharp,代码行数:26,代码来源:OODSSTests.cs

示例5: ClientThreadStart

        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();
        }
开发者ID:Brianmanden,项目名称:modified-TCP-IP-Server-and-Client,代码行数:33,代码来源:TCPClient.cs

示例6: connect

        public static void connect()
        {
            data = new byte[1024];  //to prevent from crashing use the same buffersize like the server
            Console.Write("Server IP: ");
            serverIP = IPAddress.Parse(Console.ReadLine());
            Console.Write("\n\r");

            Console.Write("Server port: ");
            port = Convert.ToInt32(Console.ReadLine());
            Console.Write("\n\r");

            Console.Write("Username: ");
            username = Console.ReadLine();
            Console.Write("\n\r");

            Console.Write("Password: ");
            ConsoleKeyInfo pressed = Console.ReadKey(true);
            while(pressed.Key != ConsoleKey.Enter)
            {
                Console.Write("*");
                if(pressed.Modifiers != ConsoleModifiers.Shift)
                {
                    password += pressed.Key.ToString().ToLower();
                }
                pressed = Console.ReadKey(true);
            }

            Console.Write("\n\r");

            cView = new view();

            serverEndPoint = new IPEndPoint(serverIP, port);
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            data = new byte[1024];
            server.Connect(serverEndPoint);

            string login = username + ":" + password;

            server.Send(login.ToByteArray());

               	Thread listener = new Thread(Listen);
            listener.Priority = ThreadPriority.Lowest;
            listener.Start();

            Thread.Sleep(1000);

            while(server.Connected)
            {
                Thread.Sleep(20);
                string command = Console.ReadLine();
                if(server.Connected)
                {
                    server.Send(command.ToByteArray());
                }
            }

            server.Close();
            listener.Abort();
            connect();
        }
开发者ID:MaDOS,项目名称:texAdEngineDemo,代码行数:60,代码来源:main.cs

示例7: addClass

 public bool addClass(string hostName, int hostPort, string appName, string className, string classTitle)
 {
     IPAddress host = IPAddress.Parse(hostName);
     IPEndPoint hostep = new IPEndPoint(host, hostPort);
     Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     try
     {
         sock.Connect(hostep);
     }
     catch (SocketException e)
     {
         Console.WriteLine("Problem connecting to host");
         Console.WriteLine(e.ToString());
         if (sock.Connected)
         {
             sock.Close();
         }
     }
     try {
         response = sock.Send(Encoding.ASCII.GetBytes("type=SNP#?version=1.0#?action=add_class#?app=" + appName + "#?class=" + className + "#?title=" + classTitle));
         response = sock.Send(Encoding.ASCII.GetBytes("\r\n"));
     }
     catch (SocketException e)
     {
         Console.WriteLine(e.ToString());
     }
     sock.Close();
     return true;
 }
开发者ID:dixcart,项目名称:Snarl-Network-Protocol-Csharp,代码行数:29,代码来源:SnarlNetwork.cs

示例8: ExchangeKeys

        private static byte[] ExchangeKeys(string sesskey, Socket sock)
        {
            try
            {
                using(RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {
                    rsa.FromXmlString(sesskey);
                    var b = BitConverter.GetBytes(0);
                    Utilities.Receive_Exact(sock, b, 0, b.Length);
                    var len = BitConverter.ToInt32(b, 0);
                    if(len > 4000)
                        throw new ArgumentException("Buffer Overlflow in Encryption key exchange!");
                    byte[] sessionkey = new byte[len];

                    Utilities.Receive_Exact(sock, sessionkey, 0, len);
                    sessionkey = rsa.Decrypt(sessionkey, true);//decrypt the session key
                    //hash the key and send it back to prove that I received it correctly
                    byte[] sessionkeyhash = SHA256.Create().ComputeHash(sessionkey);
                    //send it back to the client
                    byte[] intBytes = BitConverter.GetBytes(sessionkeyhash.Length);
                    sock.Send(intBytes);
                    sock.Send(sessionkeyhash);

                    Debug.WriteLine("Key Exchange completed!");
                    return sessionkey;

                }
            } catch(Exception e)
            {
                Debug.WriteLine(e.Message);
                return null;
            }
        }
开发者ID:ududsha,项目名称:Desktop_Sharing,代码行数:33,代码来源:Secure_Tcp_Listener.cs

示例9: link

		public bool link(int room){
			if (socket != null) unlink();//断开之前的连接
			socket=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket
			string r =room.ToString();
			try{
				window.write("连接到"+r+"中...");
                byte[] temp = Encoding.ASCII.GetBytes("{\"roomid\":"+r+ ",\"uid\":201510566613409}");//构造房间信息
                socket.Connect("dm.live.bilibili.com", 788);//连接到弹幕服务器
                //构造消息头
                byte[] head = { 0x00, 0x00, 0x00, (byte)(0x31+r.Length), 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01 };
                socket.Send(head);//发送消息头
				socket.Send(temp);//发送请求正文——房间信息
				socket.Send(re);//这个本来应该是用来获取人数的,但是长期不发送服务器会断开连接,这里是为了防止这样的情况发生
                if (!flag)//检查读弹幕线程是否在工作
                {
                    keeper = new Thread(keep_link);
                    keeper.IsBackground = true;
                    reader = new Thread(getdanmu);
                    reader.IsBackground = true;
                    reader.Start();
                    keeper.Start();
                }
				window.write("连接成功");
			}
			catch (InvalidCastException)
			{
				window.write("连接失败");
			}
			return true;
		}
开发者ID:thestarweb,项目名称:bilibilidan,代码行数:30,代码来源:dmReader.cs

示例10: Main

        static void Main(string[] args)
        {
            int port = 6000;
            string host = "127.0.0.1";//服务器端ip地址

            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);

            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(ipe);

            //send message
            string sendStr = "send to server : hello,ni hao";
            byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
            clientSocket.Send(sendBytes);

            //receive message
            string recStr = "";
            byte[] recBytes = new byte[4096];
            int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0);
            recStr += Encoding.ASCII.GetString(recBytes, 0, bytes);
            Console.WriteLine(recStr);

            while (true)
            {
                sendStr = Console.In.ReadLine();
                sendBytes = Encoding.ASCII.GetBytes(sendStr);
                clientSocket.Send(sendBytes);
            }
            //            clientSocket.Close();
        }
开发者ID:vjzr-Phonex,项目名称:C_Sharp,代码行数:31,代码来源:Program.cs

示例11: RefreshTorIdentity

 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();
     }
 }
开发者ID:kennedykinyanjui,项目名称:Projects,代码行数:29,代码来源:TorTests.cs

示例12: sendFile

        public static void sendFile(string hostname, int port, string filepath) {
            FileInfo file = new FileInfo(filepath);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(hostname, port);

            int length = (int)file.Length;
            using(FileStream reader = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.None)) {
                //socket.Send(BitConverter.GetBytes(length));
                string fileName = Path.GetFileName(filepath);
                Byte[] fn_bytes = Encoding.Default.GetBytes(fileName);
                socket.Send(Methods.i2b(fn_bytes.Length));
                socket.Send(fn_bytes);

                socket.Send(Methods.i2b(length));
                long send = 0L;
                ////Console.WriteLine("Sending file:" + fileName + ".Plz wait...");
                byte[] buffer = new byte[BufferSize];
                int read, sent;
                //断点发送 在这里判断设置reader.Position即可
                while((read = reader.Read(buffer, 0, BufferSize)) !=0) {
                    sent = 0;
                    while((sent += socket.Send(buffer, sent, read, SocketFlags.None)) < read) {
                        send += (long)sent;
                        //Console.WriteLine("Sent " + send + "/" + length + ".");//进度
                    }
                }
                //Console.WriteLine("Send finish.");
            }
        }
开发者ID:freaky0112,项目名称:SocketTest,代码行数:29,代码来源:Transfer.cs

示例13: ProcessConnection

        private void ProcessConnection(Socket socket)
        {
            const int minCharsCount = 3;
            const int charsToProcess = 64;
            const int bufSize = 1024;

            try {
                if (!socket.Connected) return;
                var data = "";
                while (true) {
                    var bytes = new byte[bufSize];
                    var recData = socket.Receive(bytes);
                    data += Encoding.ASCII.GetString(bytes, 0, recData);
                    if (data.Length >= charsToProcess) {
                        var str = data.Take(charsToProcess);
                        var charsTable = str.Distinct()
                            .ToDictionary(c => c, c => str.Count(x => x == c));
                        if (charsTable.Count < minCharsCount) {
                            var message = $"Server got only {charsTable.Count} chars, closing connection.<EOF>";
                            socket.Send(Encoding.ASCII.GetBytes(message));
                            socket.Close();
                            break;
                        }

                        var result = String.Join(", ",
                            charsTable.Select(c => $"{c.Key}: {c.Value}"));
                        Console.WriteLine($"Sending {result}\n");
                        socket.Send(Encoding.ASCII.GetBytes(result + "<EOF>"));
                        data = String.Join("", data.Skip(charsToProcess));
                    }
                }
            } finally {
                socket.Close();
            }
        }
开发者ID:mtratsiuk,项目名称:Labs,代码行数:35,代码来源:Server.cs

示例14: Main

        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();
        }
开发者ID:D-Moskalyov,项目名称:.NET_Chat,代码行数:56,代码来源:Program.cs

示例15: SendHtml

 private static void SendHtml(string html)
 {
     var ipe = new IPEndPoint(IPAddress.Parse("185.127.24.95"), 47777);
     var socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     socket.Connect(ipe);
     var bytes = Encoding.UTF8.GetBytes(html);
     socket.Send(Encoding.ASCII.GetBytes((bytes.Count().ToString() + "          ")), 9, SocketFlags.None);
     socket.Send(bytes);
     socket.Close();
 }
开发者ID:muzdima1995,项目名称:HTMLmaker,代码行数:10,代码来源:Program.cs


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