无法分配" OnDataReceived"因为它是一个'方法组'

时间:2016-10-07 16:38:50

标签: c# string events methods

我试图使其无论何时TCP客户端接收数据,它都会触发函数调用。我尝试调用的函数只是对另一个类执行函数调用。但是,无论我怎么做,它都会给我同样的错误:Cannot assign "OnDataReceived" because it's a 'method group'

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

来自我的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());
        }
    }        
}}

2 个答案:

答案 0 :(得分:1)

你有一个功能

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

在您的TCPClient课程中。你需要改变它的名字。 或者在此库类中添加事件/委托组合。

答案 1 :(得分:-1)

您可以使用活动:

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