UDPserver
使用計時器,每隔1毫秒接收資料
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace udpsever
{
public partial class Form1 : Form
{
string text2;
public delegate void AddDataDelegate();
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 5555);
UdpClient uc;
public Form1()
{
InitializeComponent();
}
private void addData()
{
label1.Text = "Waiting for a client...";
}
private void addData_1()
{
label1.Text = text2;
}
private void button1_Click(object sender, EventArgs e)
{
uc = new UdpClient(5555);
this.Invoke(new AddDataDelegate(addData));
timer1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
uc.Close();
text2 = "Stop.....";
this.Invoke(new AddDataDelegate(addData_1));
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
uc.Close();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (uc.Available != 0)
{
text2 = System.Text.Encoding.UTF8.GetString(uc.Receive(ref ipep));
this.Invoke(new AddDataDelegate(addData_1));
}
}
}
}
UDPclient
單向傳送資料
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace udpclient
{
public partial class Form1 : Form
{
IPEndPoint ipep;
Socket server;
string ip;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ip = textBox1.Text;
ipep = new IPEndPoint(IPAddress.Parse(ip), 5555);
server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
private void Form1_Load(object sender, EventArgs e)
{
ip="127.0.0.1";
textBox1.Text = ip;
}
private void button2_Click(object sender, EventArgs e)
{
string text = textBox2.Text;
byte[] sendByte = Encoding.UTF8.GetBytes(text);
server.SendTo(sendByte, ipep);
}
}
}
沒有留言:
張貼留言