暗诡刺 于 2013-09-22 15:07:07 发布 13170 收藏 6
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
定义一个类
1 | class Class1 { public const int port = 11000; public void StarListener() { UdpClient udpclient = new UdpClient(port); 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 { socket.Close(); } } public string Send(string strServer, string strContent) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPAddress ipaddress = IPAddress.Parse(strServer); byte[] btContent = Encoding.GetEncoding("gb2312").GetBytes(strContent); IPEndPoint ipendpoint = new IPEndPoint(ipaddress, port); socket.SendTo(btContent, ipendpoint); socket.Close(); return "发送成功!"; } |
服务端监听
1 | Class1 class1 = new Class1(); class1.StarListener(); |
客户端发送
1 | //textBox1是IP地址栏,textBox2是要发送的信息,button1发送按钮 Class1 class1 = new Class1(); System.Diagnostics.Process myProcess; private void Form2_Load(object sender, EventArgs e) { myProcess = System.Diagnostics.Process.Start("Server.exe");//开启服务 richTextBox1.Text = string.Empty; richTextBox1.Focus(); } private void button1_Click(object sender, EventArgs e)//发送按钮 { MessageBox.Show(class1.Send(textBox1.Text, richTextBox1.Text)); } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 13)//按下Enter的时候 richTextBox1.Focus(); } private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 13)//按下Enter的时候 button1.Focus(); } private void Form2_FormClosing(object sender, FormClosingEventArgs e) { myProcess.Kill();//关闭服务 } |
这样就可以了,先启用服务端代码,然后在客户端发送,在服务端就可以接收到发送的信息。