1,UDP客戶端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
namespace WindowsFormsApplication14
{
public partial class Form1 : Form
{
UdpClient udpClient;
IPEndPoint ipEndPoint;
public Form1()
{
InitializeComponent();
udpClient = new UdpClient(12345);
ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.241"), 60000);
}
private void button1_Click(object sender, EventArgs e)
{
//byte[] mybyte = Encoding.Default.GetBytes("nihao");
byte[] mybyte = new byte[4];
mybyte[0] = 0x12;
mybyte[1] = 0x00;
mybyte[2] = 0x34;
mybyte[3] = 0x00;
udpClient.Send(mybyte, mybyte.Length,ipEndPoint);
}
}
}
2,UDP服務器
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
namespace WindowsFormsApplication15
{
public partial class Form1 : Form
{
UdpClient udpServer;
IPEndPoint ipEndPoint;
public Form1()
{
InitializeComponent();
udpServer = new UdpClient(23456);
ipEndPoint = new IPEndPoint(new IPAddress(0), 0);
}
private void button1_Click(object sender, EventArgs e)
{
byte[] data = udpServer.Receive(ref ipEndPoint);
MessageBox.Show ( Encoding.Default.GetString(data));
}
}
}
3,讀接收緩沖區當前數據個數
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
namespace WindowsFormsApplication15
{
public partial class Form1 : Form
{
UdpClient udpServer;
IPEndPoint ipEndPoint;
public Form1()
{
InitializeComponent();
udpServer = new UdpClient(23456);
ipEndPoint = new IPEndPoint(new IPAddress(0), 0);
}
private void button1_Click(object sender, EventArgs e)
{
byte[] outValue = BitConverter.GetBytes(0);
udpServer.Client.IOControl(IOControlCode.DataToRead, null, outValue);
MessageBox.Show((BitConverter.ToInt32(outValue,0)).ToString());//發送數據發現此時數據增長,但不會超過8K
//MessageBox.Show((BitConverter.ToString(outValue)).ToString());
}
}
}
4,上例有點復雜,看下面的例子,這個例子還可以說明如何設置非阻塞Socket通訊
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
namespace WindowsFormsApplication15
{
public partial class Form1 : Form
{
UdpClient udpServer;
IPEndPoint ipEndPoint;
public Form1()
{
InitializeComponent();
udpServer = new UdpClient(23456);
ipEndPoint = new IPEndPoint(new IPAddress(0), 0);
udpServer.Client.Blocking = false; //設置為非阻塞模式
}
private void button1_Click(object sender, EventArgs e)
{