C#C
C#3y ago
Ronnie

send a response from TCP server to client

Exception says that objektreference is null

Initiates these directly in Form
c#
TcpListener _lyssnare;
TcpClient _klient;
int _port = 12345;
IPAddress _ipAddress = IPAddress.Parse("127.0.0.1");
bool _ärServerIgång;
Kodhanterare _kodhanterare = new Kodhanterare();


Starts server
c#
  public async void StartaServer()
    {
      try
      {
      _lyssnare = new TcpListener(_ipAddress, _port);
      _lyssnare.Start();
      _ärServerIgång = true;


      /// <summary>
      /// Väntar på meddelande
      /// </summary>
      try
      {
        lbl_info.Text = "väntar på koppling...";
        _klient = await _lyssnare.AcceptTcpClientAsync();
      }
      catch (ObjectDisposedException ex)
      {
      return;
      }
      lbl_info.Text = "kopplad till klient";
      StartaLäsning(_klient);
      }
      catch (Exception error)
      {
        MessageBox.Show(error.Message); return;
      }
      }


Sends back response
c#
public async void StartaSändning(string meddelande)
{
// _klient in here is NULL despite initiated in Form and "used" in StartServer()

byte[] utdata = Encoding.Unicode.GetBytes(meddelande);
    try
    {
      await _klient.GetStream().WriteAsync(utdata, 0, utdata.Length);
      }
      catch (Exception error) 
      { MessageBox.Show(error.Message); return; }
}
Was this page helpful?