C# 无法分配";OnDataReceived";因为它';s a';方法组';

C# 无法分配";OnDataReceived";因为它';s a';方法组';,c#,string,events,methods,C#,String,Events,Methods,我试图使它在TCP客户端接收数据时触发函数调用。我试图调用的函数只是对另一个类执行函数调用。但是不管我怎么尝试,它总是给我同样的错误:无法分配“OnDataReceived”,因为它是一个“方法组” 我的表格1中的代码: namespace Liberly { public partial class Form1 : Form { TcpClient tcpClient; public Form1() { InitializeComponent();

我试图使它在TCP客户端接收数据时触发函数调用。我试图调用的函数只是对另一个类执行函数调用。但是不管我怎么尝试,它总是给我同样的错误:
无法分配“OnDataReceived”,因为它是一个“方法组”

我的表格1中的代码:

namespace Liberly
{
public partial class Form1 : Form
{
    TcpClient tcpClient;
    public Form1()
    {
        InitializeComponent();
        tcpClient = new TcpClient();

        tcpClient.OnDataReceived += data;
    }
    private void data(string text)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        tcpClient.Connect("127.0.0.1", 2222);
    }
    private void button2_Click(object sender, EventArgs e)
    {
        tcpClient.Disconnect();
    }
}}
我的TCP客户端库中的代码:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Liberly
{
class TcpClient
{
    private Socket sender;
    private IPEndPoint remoteEP;
    private IPAddress ipAddress;
    private IPHostEntry ipHostInfo;
    private bool run;
    private int bytesRec;
    private string data;
    private byte[] bytes = new byte[1024];
    Thread clientT;

    /// <summary>
    /// Connect with desired ip adress and port
    /// </summary>
    /// <param name="ip">Ip address</param>
    /// <param name="port">Port</param>
    public void Connect(string ip,int port)
    {
        //Setup ip and port
        ipHostInfo = Dns.Resolve(ip);
        ipAddress = ipHostInfo.AddressList[0];
        remoteEP = new IPEndPoint(ipAddress, port);

        //Start client thread
        clientT = new Thread(new ThreadStart(client));
        run = true;
        clientT.Start();
}
    /// <summary>
    /// Disconnect from a server
    /// </summary>
    public void Disconnect()
    {
        if (run)
        {
            try
            {
                run = false;
                if (sender.Connected)
                {
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }
                clientT.Interrupt();
            }
            catch { }
        }
        else
        {
            Debug.WriteLine("TCP CLIENT/Client is not connected");
        }
    }
    /// <summary>
    /// Send data to the server
    /// </summary>
    /// <param name="text">Text</param>
    public void Send(string text)
    {
        if (sender.Connected)
            sender.Send(Encoding.ASCII.GetBytes(text));
        else
            Debug.WriteLine("TCP CLIENT/Unable to send, not connected");
    }
    /// <summary>
    /// Returns bool if client is connected to the server
    /// </summary>
    /// <returns></returns>
    public bool Connected { get { return sender.Connected; } }

    //Function that runs when data is received
    public string OnDataReceived()
    {
        return data;
    }



    //Client void
    private void client()
    {
        try {
            //Create socket and connect
            sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sender.Connect(remoteEP);
            Debug.WriteLine("TCP CLIENT/Connected");

            //Loop for receiving data
            while (run)
            {

                bytesRec = sender.Receive(bytes);
                data = Encoding.ASCII.GetString(bytes, 0, bytesRec);

                if (data != null)
                {
                    Debug.WriteLine("TCP CLIENT/Received data:" + data);
                    if (data == "")
                    {
                        Debug.WriteLine("TCP CLIENT/Disconnected");
                        break;
                    }
                    else
                    {
                        //Here is the data that is received//
                        OnDataReceived();
                    }
                }
                data = null;
            }
        }
        catch (ArgumentNullException ane)
        {
            Console.WriteLine("TCP CLIENT/ArgumentNullException : {0}", ane.ToString());
        }
        catch (SocketException se)
        {
            Console.WriteLine("TCP CLIENT/SocketException : {0}", se.ToString());
 }            catch (Exception e)
        {
            Console.WriteLine("TCP CLIENT/Unexpected exception : {0}", e.ToString());
        }
    }        
}}
使用系统;
使用System.Collections.Generic;
使用系统诊断;
使用System.Linq;
Net系统;
使用System.Net.Sockets;
使用系统文本;
使用系统线程;
使用System.Threading.Tasks;
自由名称空间
{
类TcpClient
{
专用套接字发送器;
专用iEndpoint remoteEP;
私人IP地址;
私人IPHostEntry ipHostInfo;
私人布尔运行;
私有int bytesRec;
私有字符串数据;
专用字节[]字节=新字节[1024];
线程客户端;
/// 
///连接到所需的ip地址和端口
/// 
///Ip地址
///港口
公共无效连接(字符串ip,int端口)
{
//设置ip和端口
ipHostInfo=Dns.Resolve(ip);
ipAddress=ipHostInfo.AddressList[0];
remoteEP=新的IPEndPoint(ipAddress,端口);
//启动客户端线程
clientT=newthread(newthreadstart(client));
run=true;
clientT.Start();
}
/// 
///断开与服务器的连接
/// 
公共空间断开连接()
{
如果(运行)
{
尝试
{
运行=错误;
如果(发送方已连接)
{
发送器关闭(SocketShutdown.Both);
sender.Close();
}
clientT.Interrupt();
}
捕获{}
}
其他的
{
Debug.WriteLine(“TCP客户端/客户端未连接”);
}
}
/// 
///将数据发送到服务器
/// 
///正文
公共无效发送(字符串文本)
{
如果(发送方已连接)
Send(Encoding.ASCII.GetBytes(text));
其他的
Debug.WriteLine(“TCP客户端/无法发送,未连接”);
}
/// 
///如果客户端连接到服务器,则返回bool
/// 
/// 
public bool Connected{get{return sender.Connected;}
//接收数据时运行的函数
公共字符串OnDataReceived()
{
返回数据;
}
//客户无效
私有void客户端()
{
试一试{
//创建套接字并连接
发送方=新套接字(AddressFamily.InterNetwork、SocketType.Stream、ProtocolType.Tcp);
发送方连接(remoteEP);
Debug.WriteLine(“TCP客户端/连接”);
//接收数据的环路
while(运行)
{
bytesRec=发送方.接收(字节);
数据=Encoding.ASCII.GetString(字节,0,bytesRec);
如果(数据!=null)
{
Debug.WriteLine(“TCP客户端/接收数据:+数据”);
如果(数据==“”)
{
Debug.WriteLine(“TCP客户端/断开连接”);
打破
}
其他的
{
//这是收到的数据//
OnDataReceived();
}
}
数据=空;
}
}
捕集物(捕集物)
{
WriteLine(“TCP客户端/ArgumentNullException:{0}”,ane.ToString());
}
捕获(SocketException se)
{
WriteLine(“TCP客户端/SocketException:{0}”,se.ToString());
}捕获(例外e)
{
WriteLine(“TCP客户端/意外异常:{0}”,e.ToString());
}
}        
}}
您有一个函数

  //Function that runs when data is received
    public string OnDataReceived()
    {
        return data;
    }
在您的
TCPClient
类中。您需要更改它的名称。 或者在此库类中添加事件/委托组合。

您可以使用事件:

 public delegate void onDataReceivedEvent(string message);
 public event onDataReceivedEvent onDataReceived;
 public void sendNewData(string message){
      if(!onDataReceived!=null){
             onDataReceived.Invoke(message);
      }
 }
然后注册您的活动:

 onDataReceived+= someMethod;

 private void someMethod(string message){
     //process message;
 }