这里是定义委托和事件
public delegate void MyEvent(string ReceiveMsg);//定义一个委托,用来将接收数据传出去
public event MyEvent HaveYourMsg;
但是下面用HaveYourMsg的Invoke是怎么回事,Invoke是哪里来的干什么用,为什么能用HaveYourMsg调用呢?
HaveYourMsg.Invoke(Encoding.UTF8.GetString(arrserverrecmsg, 0, length));
HaveYourMsg.Invoke("警告:您的连接已断开!!!");
在form1类中下面这个方法是怎么调用的?
private void HaveMyMsg(string Msg)
{
//使用内联委托处理多线程调用窗体控件的问题
this.Invoke(new Deal(() =>
{
textBox1.Text += Msg + "\r\n";
}));
}
全部代码
关于socket的一个类
class SocketTest
{
private Socket MySocket;
//开启一个线程循环执行接收方法来实时接收数据
private Thread ReceiveThread;
public delegate void MyEvent(string ReceiveMsg);//定义一个委托,用来将接收数据传出去
public event MyEvent HaveYourMsg;
//用于客户端连接服务端
public bool Connect(IPAddress iP, int port)
{
try
{
MySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(iP, port);
MySocket.Connect(endPoint);
return true;
}
catch
{
return false;
}
}
public bool Send(string str)
{
try
{
byte[] arrsendmsg = Encoding.UTF8.GetBytes(str);
if (MySocket.Send(arrsendmsg) != arrsendmsg.Length)
return false;
return true;
}
catch
{
return false;
}
}
public void recmsg()
{
while (true)
{
try
{
byte[] arrserverrecmsg = new byte[1024];
int length = MySocket.Receive(arrserverrecmsg);
if (length > 0)
{
HaveYourMsg.Invoke(Encoding.UTF8.GetString(arrserverrecmsg, 0, length));
}
}
catch
{
HaveYourMsg.Invoke("警告:您的连接已断开!!!");
return;
}
Thread.Sleep(200);
}
}
public void StartReceive()
{
ReceiveThread = new Thread(recmsg);
ReceiveThread.IsBackground = true;
ReceiveThread.Start();
}
public void CloseSocket()
{
//如果接收线程正在执行那么先关闭线程在关闭socket
if (ReceiveThread.ThreadState == ThreadState.Running)
ReceiveThread.Abort();
MySocket.Close();
}
}
form1类
public partial class Form1 : Form
{
private delegate void Deal();
public Form1()
{
InitializeComponent();
}
SocketTest socketTest;
private void Form1_Load(object sender, EventArgs e)
{
socketTest = new SocketTest();
if (!socketTest.Connect(IPAddress.Parse("127.0.0.1"), 20000))
{
MessageBox.Show("连接服务端失败,请重试!");
}
//绑定事件接收函数,当有消息时会触发该函数
socketTest.HaveYourMsg += new SocketTest.MyEvent(HaveMyMsg);
socketTest.StartReceive();
}
private void Button1_Click(object sender, EventArgs e)
{
if (textBox2.Text.Length <= 0)
{
MessageBox.Show("不允许发送空内容");
return;
}
if (!socketTest.Send(textBox2.Text))
{
MessageBox.Show("发送失败了");
return;
}
textBox2.Clear();
}
private void HaveMyMsg(string Msg)
{
//使用内联委托处理多线程调用窗体控件的问题
this.Invoke(new Deal(() =>
{
textBox1.Text += Msg + "\r\n";
}));
}
}