【例1】下面演示如何使用C#制作一个局域网聊天程序,程序开发步骤如下:
(1)新建一个Windows应用程序,并命名为11,这时程序自动创建了一个解决方案,名称为11。
(2)将默认创建的Windows 窗体删除,然后在名称为 11 的解决方案下添加一个类和两个 Windows项目。其中,类文件用来封装接收信息和发送信息的方法,两个Windows 项目分别用来作为聊天程序的服务器端和客户端。
(3)类文件的主要代码始下:
public const int port =11000; //设置端口号
public void StartListener()
{
UdpClient udpclient=newUdpClient(port);
IPEndPoint ipendpoint=newIPEndPoint(IPAddress.Any,port); //将网络端点表示为IP地址和端口号
try
{
while(true)
{
byte[]) bytes=udpclient.Receive(ref ipendpoint);
string strIP=”信息来自”+ ipendpoint.Address.ToString();
string striInfo =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.lnterNetwork,SocketType.Dgram, ProtocolType.Udp);
IPAddress ipaddress = IPAddress.Parse(strServer); //将输入的字符串转换为 IP 地址
//将发送的内容存储到byte 数组中
byte[ ]btContent= Encoding.GetEncoding(“gb2312").GetBytes(strContent );IPEndPoint ipendpoint = new IPEndPoint(ipaddress,11000);socket.SendTo(btContent, ipendpoint);
socket.Close();
return "发送成功”;
}
注意
①编写公共类文件时,需要在命名空间区城添加 using System.Text、using System.Net.Sockets.、using System.Net 和 using System. Windows.Forms 命名空间。
②编写完公共类之后,需要使用“csc/t:library类文件名”命令在“Visual Studio 2010 命今提示”工具中将类文件编译为.dll文件,以便在服务器端和客户瑞添加调用。
(4)服务器端主要代码如下:
Class1 class1=newClass1();
private void Form1_Load(objectsender, EventArgs e)
{
this. Hide(); //隐藏当前窗体
class1.StartListener(); //调用公共类中的方法接受信息
}
(5)客户端主要代码如下:
Class1 class1=newClass1();
System.Diagnostics.ProcessmyProcess;
private void Form1_Load(objectsender, EventArgs e)
{
myProcess=System.Diagnostics.Process.Start(“Server.exe”);//开启服务
}
//“发送”按钮事件
private void btnSend_Click(objectsender, EventArgs e)
{
MessageBox.Show(class1.Send(txtServer.Text,txtInfo.Text)); //发送信息
txtInfo.Text=string.Empty.;
txtInfo.Focus();
}
//当在“聊天服务器”文本框中输入内容,按下 Enter 键时,将鼠标焦点移动到“信息”文本框中
private void txtServer_KeyPress(objectsender, KeyPressEventArgs e)
{
If(e.KeyChar==13)
txtInfo.Focus();
}
//当在“信息”文本框中输入内容,按下 Enter 键时,将鼠标焦点移动到“发送”按钮上
private void txtInfo_KeyPress(objectsender, KeyPressEventArgs e)
{
If(e.KeyChar==13)
btnSend.Focus();
}
//窗体关闭事件
private void Form1_FormClosing(objectsender, FormClosingEventArgs e)
{
myProcess.Kill(); //关闭服务
}
程序的运行结果如下图所示。