简单UDP链接,发送文字到服务端

1、服务端,启动监听循环

  Class1 class1 = new Class1();
        private void Form1_Load(object sender, EventArgs e)
        {
            this.Hide();                    //隐藏当前窗体
            class1.StartListener();     //调用公共类中的方法接收信息
        }

 公共类Class1

public class Class1
{
    public Class1()
    {
    }
    //设置端口号
    public const int port = 11000;
    public void StartListener()
    {
        UdpClient udpclient = new UdpClient(port);
        //将网络端点表示为IP地址和端口号
        IPEndPoint ipendpoint = new IPEndPoint(IPAddress.Any, port);
        try
        {
            while (true)
            {
                byte[] bytes = udpclient.Receive(ref ipendpoint);
                string strIP = "信息来自" + ipendpoint.Address.ToString();
                string strInfo = Encoding.GetEncoding("gb2312").GetString(bytes, 0, bytes.Length);
                MessageBox.Show(strInfo, strIP);
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }
        finally
        {
            udpclient.Close();
        }
    }
    public string Send(string strServer,string strContent)
    {
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        //将输入的字符串转换为IP地址
        IPAddress ipaddress = IPAddress.Parse(strServer);
        //将发送的内容存储到byte数组中
        byte[] btContent = Encoding.GetEncoding("gb2312").GetBytes(strContent);
        IPEndPoint ipendpoint = new IPEndPoint(ipaddress, 11000); // 此处绑定服务端的IP和 Port
        socket.SendTo(btContent, ipendpoint);
        socket.Close();
        return "发送成功";
    }
}

2、客户端

 Class1 class1 = new Class1();
        System.Diagnostics.Process myProcess;
        private void Form1_Load(object sender, EventArgs e)
        {
            myProcess = System.Diagnostics.Process.Start("Server.exe");//开启服务
        }
        //“发送”按钮事件
        private void btnSend_Click(object sender, EventArgs e)
        {
            MessageBox.Show(class1.Send(txtServer.Text, txtInfo.Text));//发送信息
            txtInfo.Text = string.Empty;
            txtInfo.Focus();
        }
        //当在“聊天服务器”文本框中输入内容,按下回车键时,将鼠标焦点移动到“信息”文本框中
        private void txtServer_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
                txtInfo.Focus();
        }
        //当在“信息”文本框中输入内容,按下回车键时,将鼠标焦点移动到“发送”按钮上
        private void txtInfo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
                btnSend.Focus();
        }
        //窗体关闭事件
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            myProcess.Kill();                                         //关闭服务
        }

 

posted @ 2016-04-25 23:36  海蓝7  阅读(178)  评论(0)    收藏  举报