简体   繁体   中英

Cannot assign "OnDataReceived" because it's a 'method group'

I'm trying to make it so that whenever a TCP client receives data, it triggers a function call. The function I'm trying to call just performs a function call on another class. But however I try it, it keeps giving me the same error: Cannot assign "OnDataReceived" because it's a 'method group'

Code from my form1:

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();
    }
}}

Code from my TCP client library:

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());
        }
    }        
}}

You have a function

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

in your TCPClient class. You need to change its name. Or add a event / delegate combo in this library class.

You can use events:

 public delegate void onDataReceivedEvent(string message);
 public event onDataReceivedEvent onDataReceived;
 public void sendNewData(string message){
      if(!onDataReceived!=null){
             onDataReceived.Invoke(message);
      }
 }

Then register your event:

 onDataReceived+= someMethod;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM