原文地址:https://blog.csdn.net/anxin591025/article/details/11898241
定义一个类
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 "发送成功!";
}
服务端监听
Class1 class1 = new Class1();
class1.StarListener();
客户端发送
//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();//关闭服务
}
网友评论