.net中axWinsock 监听多个客户端
2020-12-13 14:38
标签:style io color os ar for sp strong on 网上针对于.net中的axWinsock 控件的资料比较少,而且案例更是少的可怜。 前段时间一直在折磨 axWinsock 如何监听多个客户端。现在终于把它弄出来了,希望能帮到需要的人。 服务器端: 添加axWinsock 控件到窗体中。在控件属性中设置端口 LocalPort 如:1001,IP地址LocalIP,控件会自动绑定了。 1、在窗体加载事件中开启axWinsock1监听 private void Form1_Load(object sender, EventArgs e) 2、在窗体后台代码创建两个事件 (1)接收发送事件 private void ax_DataArrival(object sender, AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent e) (2)axWinsock断开事件 private void ax_CloseEvent(object sender, EventArgs e) 3、给axWinsock ConnectionRequest事件中添加以下代码 int k; private void axWinsock1_ConnectionRequest(object sender, AxMSWinsockLib.DMSWinsockControlEvents_ConnectionRequestEvent e) //创建AxWinsock 控件绑定不同的客户端,并且添加到窗体中 } 服务器已经创建完毕 ============================================================================================================ 客户端: 1、在客户端窗体中添加axWinsock控件 2、在窗体加载中开启axWinsock 连接服务器 private void Form1_Load(object sender, EventArgs e) 3、给axWinsock控件中的ConnectionRequest事件中接收服务器发来的信息 private void axWinsock1_DataArrival(object sender, AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent e) 4、发送信息 //发送按钮事件 private void button2_Click(object sender, EventArgs e) .net中axWinsock 监听多个客户端 标签:style io color os ar for sp strong on 原文地址:http://blog.csdn.net/cai_ethan/article/details/40650383
{
axWinsock1.Listen();//开启监听
}
{
try
{
object data = "";
AxMSWinsockLib.AxWinsock sendsock = (AxMSWinsockLib.AxWinsock)sender;
sendsock.GetData(ref data);//接收
sendsock.SendData(sendsock.RemoteHostIP + ":" + sendsock.RemotePort + ",知道了,客户端。我是服务器!" + "\n");//发送
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
{
AxMSWinsockLib.AxWinsock sendsock = (AxMSWinsockLib.AxWinsock)sender;
socklist.Remove(sendsock);
this.Controls.Remove(sendsock);
}
{
AxMSWinsockLib.AxWinsock axsock = new AxMSWinsockLib.AxWinsock();
axsock.Name = (axsock + e.requestID.ToString() + k.ToString());
((System.ComponentModel.ISupportInitialize)(axsock)).BeginInit();
this.Controls.Add(axsock);
int rows = this.Controls.Count;
((System.ComponentModel.ISupportInitialize)(axsock)).EndInit();
axsock.Accept(e.requestID);
k++;
axsock.DataArrival += ax_DataArrival;//给客户端绑定接收发送事件
axsock.CloseEvent += ax_CloseEvent;
{
axWinsock1.Connect(服务器IP, 服务器端口);
}
{
object data = "";
axWinsock1.GetData(ref data);
richTextBox1.AppendText((String)data+"\n");
}
{
axWinsock1.SendData("我是客户端啊!");
}