udp发送接收数据

using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace jieshou
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
                Jie();
        }


        
static void Jie()
        
{
            
int i = 0;

             Socket socket 
= new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//初始化一个Scoket协议

            IPEndPoint iep 
= new IPEndPoint(IPAddress.Any, 3000);//初始化一个侦听局域网内部所有IP和指定端口

            EndPoint ep 
= (EndPoint)iep;

            socket.Bind(iep);
//绑定这个实例

            
while (true)
            
{
                
byte[] buffer = new byte[1024];//设置缓冲数据流

                socket.ReceiveFrom(buffer, 
ref ep);//接收数据,并确把数据设置到缓冲流里面

                Console.WriteLine(Encoding.Unicode.GetString(buffer).TrimEnd(
'\u0000'+ " " + i.ToString());

                i
++;
            }

        }

    }

}




using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace guangbo
{
    
class Program
    
{
        
//private Thread trd;
        public int num = 0;

        
static void Main(string[] args)
        
{
            
//Thread trd = new Thread(new ThreadStart(guangbo()));
            
//trd.IsBackground = true;
            
//trd.Start();
            for (int i = 0; i < 10000; i++)
            
{
                Console.WriteLine(i);
                
//Thread.Sleep(10000);
                Guang();
            }

            Console.ReadKey();
        }


        
static  void Guang()
        
{
            Socket sock 
= new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//初始化一个Scoket实习,采用UDP传输

            IPAddress ip 
= IPAddress.Parse("192.168.111.195");

            
//ip可以用IPAddress.Any来代替全发送。

            IPEndPoint iep 
= new IPEndPoint(ip, 3000);//初始化一个发送广播和指定端口的网络端口实例

            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 
1);//设置该scoket实例的发送形式


            
string request ="你好,hi";//初始化需要发送而的发送数据

            
byte[] buffer = Encoding.Unicode.GetBytes(request);

            sock.SendTo(buffer, iep);

            sock.Close();            
            
            
//Console.WriteLine("nihao");
        }

    }

}

posted @ 2008-07-21 10:42  陈旭85  阅读(943)  评论(0编辑  收藏  举报