现在的位置: 首页 > 综合 > 正文

Socket(UDP)通信winform demo

2013年10月31日 ⁄ 综合 ⁄ 共 1371字 ⁄ 字号 评论关闭
客户端:
窗体设计--一个listbox
namespace Client
{
    public partial class MainlForm : Form
    {
        public MainlForm()
        {
            InitializeComponent();
        }
        private void MainlForm_Load(object sender, EventArgs e)
        {
            Thread myThread = new Thread(ReceiveData);
            myThread.IsBackground = true;
            myThread.Start();
        }
        private UdpClient receiveUdpClient;
        private void ReceiveData()
        {
            IPEndPoint local = new IPEndPoint(IPAddress.Any, 8008);
            receiveUdpClient = new UdpClient(local);
            IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                byte[] receiveBytes = receiveUdpClient.Receive(ref remote);
                string receiveMessage = Encoding.UTF8.GetString(receiveBytes, 0, receiveBytes.Length);
                AddItem(lst_Receive, receiveMessage);
            }
        }
        delegate void AddItemDelegate(ListBox listbox, string text);
        private void AddItem(ListBox listbox, string text)
        {
            if (listbox.InvokeRequired)
            {
                AddItemDelegate d = AddItem;
                listbox.Invoke(d, new object[] { listbox, text });
            }
            else
            {
                listbox.Items.Add(text);
                listbox.SelectedIndex = listbox.Items.Count - 1;
                listbox.ClearSelected();
            }
        }
    }
}
 
服务器端:
窗体设计--1.远程IP textbox 2.远程Porttextbox 3.发送消息内容 textbox 4.发送button
namespace Server
{
    public partial class MainForm : Form
    {
        UdpClient myUdpClient = new UdpClient();
        public MainForm()
        {
            InitializeComponent();
        }
        private void btnSend_Click(object sender, EventArgs e)
        {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(textMsg.Text);
            IPEndPoint local = new IPEndPoint(IPAddress.Parse(remoteIp.Text), int.Parse(remotePort.Text));
            myUdpClient.Send(bytes, bytes.Length, local);
            textMsg.Text = "";
        }
    }
}

抱歉!评论已关闭.