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


C# Socket.SendTo方法代码示例

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


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

示例1: Main

 static void Main(string[] args)
 {
     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9000);
     s.Bind(iep);
     EndPoint remote = (EndPoint)iep;
     byte[] data = new byte[1024];
     int k = s.ReceiveFrom(data, ref remote);
     Console.WriteLine("Loi chao tu Client:{0}",Encoding.ASCII.GetString(data,0,k));
     data = new byte[1024];
     data = Encoding.ASCII.GetBytes("Chao Client ket noi");
     s.SendTo(data, remote);
     while (true)
     {
         data = new byte[1024];
         string st;
         k=s.ReceiveFrom(data, ref remote);
         st = Encoding.ASCII.GetString(data, 0, k);
         Console.WriteLine("Du lieu tu Client Gui la:{0}", st);
         if (st.ToUpper().Equals("QUIT"))
             break;
         st = st.ToUpper();
         data = new byte[1024];
         data = Encoding.ASCII.GetBytes(st);
         s.SendTo(data, remote);
     }
     s.Close();
 }
开发者ID:pthdnq,项目名称:csharp-project-nduang,代码行数:28,代码来源:Program.cs

示例2: Main

 static void Main(string[] args)
 {
     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000);
     string st = "Chao Server";
     byte[] data = new byte[1024];
     data = Encoding.ASCII.GetBytes(st);
     s.SendTo(data, iep);
     EndPoint remote=(EndPoint)iep;
     data = new byte[1024];
     int k=s.ReceiveFrom(data,ref remote);
     Console.WriteLine("Loi chao tu Server:{0}", Encoding.ASCII.GetString(data, 0, k));
     while (true)
     {
         Console.Write("Nhap du lieu gui len Server:");
         string st1 = Console.ReadLine();
         byte[] dl = new byte[1024];
         dl = Encoding.ASCII.GetBytes(st1);
         s.SendTo(dl, remote);
         if (st1.ToUpper().Equals("QUIT"))
             break;
         dl = new byte[1024];
         int k1=s.ReceiveFrom(dl, ref remote);
         Console.WriteLine("Du lieu tu Server la:{0}", Encoding.ASCII.GetString(dl, 0, k1));
     }
     s.Close();
 }
开发者ID:pthdnq,项目名称:csharp-project-nduang,代码行数:27,代码来源:Program.cs

示例3: Main

 static void Main(string[] args)
 {
     byte[] data = new byte[1024];
     string input, stringData;
     IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("38.98.173.2"), 58642);
     //IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 58642);
     Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     string welcome = "Hello, are you there?";
     data = Encoding.ASCII.GetBytes(welcome);
     server.SendTo(data, data.Length, SocketFlags.None, ipep);
     IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
     EndPoint Remote = (EndPoint)sender;
     data = new byte[1024];
     int recv = server.ReceiveFrom(data, ref Remote);
     Console.WriteLine("Message received from {0}:", Remote.ToString());
     Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
     while (true)
     {
         input = Console.ReadLine();
         if (input == "exit")
             break;
         server.SendTo(Encoding.ASCII.GetBytes(input), Remote);
         data = new byte[1024];
         recv = server.ReceiveFrom(data, ref Remote);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         Console.WriteLine(stringData);
     }
     Console.WriteLine("Stopping client");
     server.Close();
 }
开发者ID:penneyworth1,项目名称:UPDTestClient,代码行数:30,代码来源:Program.cs

示例4: Discover

        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;
            }
        }
开发者ID:ninedrafted,项目名称:MCForge-Vanilla,代码行数:35,代码来源:UPnP.cs

示例5: Discover

        public static string Discover()
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            string req = "M-SEARCH * HTTP/1.1\r\n" +
            "HOST: 239.255.255.250:1900\r\n" +
            "ST:upnp:rootdevice\r\n" +
            "MAN:\"ssdp:discover\"\r\n" +
            "MX:3\r\n\r\n";
            byte[] data = Encoding.ASCII.GetBytes(req);
            IPEndPoint ipe = new IPEndPoint(IPAddress.Broadcast, 1900);
            byte[] buffer = new byte[0x1000];

            DateTime start = DateTime.Now;
            WriteLineInFile("debug.txt", ipe.Address.ToString() + ";" + ipe.AddressFamily.ToString() + ";" + ipe.Port.ToString());
            do
            {
                s.SendTo(data, ipe);
                s.SendTo(data, ipe);
                s.SendTo(data, ipe);

                WriteLineInFile("debug.txt", "Sended");

                int length = 0;
                do
                {
                    try
                    {
                        length = s.Receive(buffer);
                    }
                    catch (SocketException e)
                    {
                        WriteLineInFile("debug.txt", e.Message+" Error code: "+ e.ErrorCode);
                    }

                    WriteLineInFile("debug.txt", "lenght:" + length);
                    /*
                    string resp = Encoding.ASCII.GetString(buffer, 0, length).ToLower();
                    if (resp.Contains("upnp:rootdevice"))*/
                    string resp = Encoding.ASCII.GetString(buffer, 0, length);
                    if (resp.ToLower().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 "_descUrl=" + _descUrl + "\n_serviceUrl=" + _serviceUrl;
                        }
                    }
                } while (length > 0 && start.Subtract(DateTime.Now) < _timeout);
            } while (start.Subtract(DateTime.Now) < _timeout);
            return "false";
        }
开发者ID:JyBP,项目名称:SupChat,代码行数:54,代码来源:UPnP.cs

示例6: Discover

        public bool Discover()
        {
            Disconnect();

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            string req = "M-SEARCH * HTTP/1.1\r\n" +
            "HOST: 239.255.255.250:1900\r\n" +
            "ST:upnp:rootdevice\r\n" +
            "MAN:\"ssdp:discover\"\r\n" +
            "MX:3\r\n\r\n";
            byte[] data = Encoding.ASCII.GetBytes(req);
            IPEndPoint ipe = new IPEndPoint(IPAddress.Broadcast, 1900);
            byte[] buffer = new byte[0x1000];

            DateTime start = DateTime.Now;

            try
            {
                do
                {
                    _socket.SendTo(data, ipe);
                    _socket.SendTo(data, ipe);
                    _socket.SendTo(data, ipe);

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

                        string resp = Encoding.ASCII.GetString(buffer, 0, length).ToLower();
                        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);
            }
            catch (Exception e)
            {
                Debug.Log("error: " + e.ToString());
            }

            return false;
        }
开发者ID:edwonia,项目名称:VR-Online,代码行数:51,代码来源:UPnP.cs

示例7: BroadcastFinder

        public BroadcastFinder()
        {
            Server = "";
            IPAddress[] a = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            string broadcastAddress = "";
            foreach (IPAddress t in a)
            {
                if (!t.ToString().Contains(":"))
                {
                    broadcastAddress = t.ToString();
                    break;
                }
            }
            Port = 2080;
            broadcastAddress = broadcastAddress.Substring(0, broadcastAddress.LastIndexOf('.')) + ".255";

            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 61111);
            IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse(broadcastAddress), 61111);
            EndPoint ep = (EndPoint)iep;

            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            sock.ReceiveTimeout = 200;

            byte[] bs = Encoding.ASCII.GetBytes("Amleto client search");

            for (int i = 0; i < 3; i++)
            {
                try
                {
                    sock.SendTo(bs, iep);
                    sock.SendTo(bs, iep2);

                    byte[] data = new byte[1024];
                    int res = sock.ReceiveFrom(data, ref ep);
                    string sres = Encoding.ASCII.GetString(data, 0, res);
                    string[] parts = sres.Split(' ');

                    if (parts[0] == "Amleto" && parts[1] == "server")
                    {
                        Server = parts[3];
                        Port = Convert.ToInt32(parts[4]);
                        break;
                    }
                }
                catch (Exception)
                {
                    // Don't log exception here as this is expected to fail if server isn't running
                }
            }
        }
开发者ID:SteveMoody73,项目名称:Amleto,代码行数:51,代码来源:BroadcastFinder.cs

示例8: SendName

        public void SendName(string name)
        {
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 8101);
            IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse(this.ip), 8101);

            string username =name ;
            byte[] data = Encoding.ASCII.GetBytes("*us*"+username);

            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            sock.SendTo(data, iep1);
            sock.SendTo(data, iep2);
            sock.Close();
        }
开发者ID:RuzikM,项目名称:Chat,代码行数:14,代码来源:Clients.cs

示例9: sendBroadcastAnswer

        static void sendBroadcastAnswer()
        {
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);
            IPEndPoint iep2 = new IPEndPoint(Internet.GetMaxBroadcast(), BroadcastSendPort);

            byte[] data = Encoding.ASCII.GetBytes(Internet.GetLocalIP().ToString());

            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            try { sock.SendTo(data, iep1); }
            catch { }
            try { sock.SendTo(data, iep2); }
            catch { }
            sock.Close();
        }
开发者ID:jiashida,项目名称:super-trojan-horse,代码行数:15,代码来源:BroadCastWaiter.cs

示例10: Send

 static void Send(byte[] data, string ip, int port)
 {
     Console.WriteLine(string.Format("Sending {0} bytes...", data.Length));
     Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
     sock.SendTo(data, endPoint);
 }
开发者ID:rubenhak,项目名称:NetflowExporterCS,代码行数:7,代码来源:Program.cs

示例11: start

        public override void start()
        {
            new Thread((ThreadStart)
                delegate()//不断发送广播
                {
                    Socket sockCon = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    sockCon.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
#if UNITY_EDITOR
                    sockCon.Bind(new IPEndPoint(IPAddress.Parse(IPManager.getLanIP()), 13000));
#endif
                    IPEndPoint broad = new IPEndPoint(IPAddress.Broadcast, Const.PORT);

                    byte[] msg = new byte[4];

                    while (!isRunning)//当两个客户端(含自己)都连接成功后,isRunning将变为true,即广播结束
                    {
                        sockCon.SendTo(msg, broad);
                        Thread.Sleep(50);
                    }

                    sockCon.Close();
                    Console.WriteLine("stop sending broadcast");
                }
            ).Start();//开始广播自己

            base.start(IPManager.getLanIP());//启动tcp连接侦听
        }
开发者ID:zhendery,项目名称:FiveVsFive,代码行数:27,代码来源:LanServer.cs

示例12: Write

		/// <summary>
		/// Writes the IcmpPacket to the wire over the specified socket to the specified end point
		/// </summary>
		/// <param name="socket">The socket to write to</param>
		/// <param name="packet">The packet to write</param>
		/// <param name="ep">The end point to write to</param>
		/// <returns></returns>
		public virtual int Write(Socket socket, IcmpPacket packet, EndPoint ep)
		{
			/*
			 * check the parameters
			 * */

			if (socket == null)
				throw new ArgumentNullException("socket");

			if (socket == null)
				throw new ArgumentNullException("packet");

			if (socket == null)
				throw new ArgumentNullException("ep");

			// convert the packet to a byte array
			byte[] bytes = IcmpPacket.GetBytes(packet);

			// send the data using the specified socket, returning the number of bytes sent
			int bytesSent = socket.SendTo(bytes, bytes.Length, SocketFlags.None, ep);

			/*
			 * validate bytes sent
			 * */

			return bytesSent;
		}
开发者ID:FireBall1725,项目名称:Razor.Framework,代码行数:34,代码来源:IcmpPacketWriter.cs

示例13: Main

        static void Main(string[] args)
        {
            long i = 0;
            bool down = false;
            string message;

            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPAddress broadcast = IPAddress.Parse("192.168.1.255");
            IPEndPoint ep = new IPEndPoint(broadcast, 12345);

            while (true)
            {
                message = i.ToString() + "," + (i + 1).ToString() + "," + (i + 2).ToString() + "," + (i + 3).ToString() + "," + (i + 4).ToString() + "," + (i + 5).ToString();
                byte[] sendbuf = Encoding.ASCII.GetBytes(message);

                s.SendTo(sendbuf, ep);

                Thread.Sleep(10);
                if (!down)
                    i += 3;
                else
                    i -= 3;

                if (!down && i >= 400)
                    down = true;
                else if (down && i <= 0)
                    down = false;
            }
        }
开发者ID:eraumotorsports,项目名称:carLogger,代码行数:29,代码来源:Program.cs

示例14: button4_Click

 private void button4_Click(object sender, EventArgs e)
 {
     Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP);
     socket.SendTo(System.Text.Encoding.Unicode.GetBytes(textBox2.Text), new IPEndPoint(IPAddress.Parse("10.2.21.255"), 100));
     socket.Shutdown(SocketShutdown.Send);
     socket.Close();
 }
开发者ID:xs2ranjeet,项目名称:13ns9-1spr,代码行数:7,代码来源:Form1.cs

示例15: SendMsg

        public void SendMsg()
        {
            using ( Socket socket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ) )
            {

                StringBuilder sb = new StringBuilder();

                string sessionID = Guid.NewGuid().ToString();

                for ( int i = 0; i < 1; i++ )
                {
                    sb.Append( "$" ); //Protocol Header
                    sb.Append( "005" ); //Operation length
                    sb.Append( "LogIn" ); //Operation name

                    string command = sb.ToString();

                    Player user = new Player( "test", "123qqq" );
                    byte [] Object = Utils.ObjectToBytes( user );

                    MyRequestInfo Info = new MyRequestInfo( command, sessionID, Object );

                    socket.SendTo( Info.ToData(), serverAddress );

                    //socket.ReceiveTimeout = 1000;
                    string[] res = m_Encoding.GetString( ReceiveMessage( socket, serverAddress ).ToArray() ).Split( ' ' );

                }
            }
        }
开发者ID:Dvok,项目名称:GServer,代码行数:30,代码来源:TestClient.cs


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