TCP通信用委托刷新消息
1.在TcpHelper中声明委托
public delegate void PushSockets(Sockets sockets);
public static PushSockets pushSockets;
2.在使用的地方,比如CLientDemo的Form_Load内实例化委托,并将要执行的函数导入委托
private void Form1_Load(object sender, EventArgs e)
{
//客户端如何处理异常等信息参照服务端
SocketHelper.pushSockets = new SocketHelper.PushSockets(Rec);//注册推送器
client = new SocketHelper.TcpClients();
ip = txtIP.Text;
port = txtPort.Text;
}
3.定义要执行的函数Rec
private void Rec(SocketHelper.Sockets sks)
{
this.Invoke(new ThreadStart(delegate
{
if (infolist.Items.Count > 1000)
{
infolist.Items.Clear();
}
if (sks.ex != null)
{
//在这里判断ErrorCode 可以自由扩展
switch (sks.ErrorCode)
{
case SocketHelper.Sockets.ErrorCodes.objectNull:
break;
case SocketHelper.Sockets.ErrorCodes.ConnectError:
break;
case SocketHelper.Sockets.ErrorCodes.ConnectSuccess:
statuslist.Items.Add("连接成功.!");
break;
case SocketHelper.Sockets.ErrorCodes.TrySendData:
break;
default:
break;
}
infolist.Items.Add(string.Format("客户端信息{0}", sks.ex));
}
else
{
byte[] buffer = new byte[sks.Offset];
Array.Copy(sks.RecBuffer, buffer, sks.Offset);
string str = Encoding.UTF8.GetString(buffer);
if (str == "ServerOff")
{
infolist.Items.Add("服务端主动关闭");
}
else
{
infolist.Items.Add(string.Format("服务端{0}发来消息:{1}", sks.Ip, str));
txtThis.Text += "\r\n";
txtThis.Text += string.Format("服务端{0}发来消息:{1}", sks.Ip, str);
}
}
}));
}
注:在Rec函数内使用this.Invoke是以为要刷新界面listbox控件,new ThreadStart则可用也可不用,写成new EventHandler也可以