Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
while I am trying following simple code its throws and error of network Stream has null reference when using stream.write()

What I have tried:

This is server code:
C#
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnSendCommand_Click(object sender, EventArgs e)
    {
        string message = "SCICOM ECIL BARC|ZONE 000|SERVER 000|127.0.0.1|TVFS 007|Zone 003|127.0.0.1|GET_STAT|BARC ECIL SCICOM";
        Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
        //string HostName = txtHost.Text;
        //int prt = Int32.Parse(txtPort.Text);

        TcpClient tc = new TcpClient("127.0.0.1", 8080);

        NetworkStream ns = tc.GetStream();
                    
        ns.Write(data, 0, data.Length);
        MessageBox.Show("Command is send.");
        data = new Byte[256];

        // String to store the response ASCII representation.
        String responseData = String.Empty;

        // Read the first batch of the TcpServer response bytes.
        Int32 bytes = ns.Read(data, 0, data.Length);
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
        txtResponseShow.Text = responseData;
        Console.WriteLine("Received: {0}", responseData);

        // Close everything.
        
        
        ns.Close();
        tc.Close(); 
    }

    
}

this is client code:
C#
public partial class Form1 : Form
{
    static IPAddress localAddr = IPAddress.Parse("127.0.0.1");
    NetworkStream stream;
   
    
  
   String responseData = "";
    
    public Form1()
    {
        InitializeComponent();
        
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        label1.Visible = false; label2.Visible = false; label3.Visible = false; label4.Visible = false; label5.Visible = false; label6.Visible = false;
        txtZoneId.Visible = false; txtUnitId.Visible = false; txtSupplyVtg.Visible = false; txtTemp.Visible = false; txtBatteryStatus.Visible = false;
        cbUnitStatus.Visible = false;
    }

    private void btnStart_Click(object sender, EventArgs e)
    {

        TcpListener listener = new TcpListener(localAddr, 8080);
        listener.Start();
        MessageBox.Show("Simulator started");
        Byte[] bytes = new Byte[256];
        String data = null;

        //while(true)
        {
            Console.Write("Waiting for a connection....");
            TcpClient clientSocket = listener.AcceptTcpClient();
            Console.WriteLine("Connected!");
            //TcpClient tc = new TcpClient("127.0.0.1", 8080);

            
            data = null;

            // Get a stream object for reading and writing
            stream = clientSocket.GetStream();

            int i = stream.Read(bytes, 0, bytes.Length);

            // Loop to receive all the data sent by the client.
            //while((i = stream.Read(bytes, 0, bytes.Length))!=0)
            {
                
                // Translate data bytes to a ASCII string.
                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                Console.WriteLine("Received: {0}", data);
                //............split string using | and save in array..............
                 char[] spearator = { '|' };
                 String[] dataStr = data.Split(spearator, 9);
                //.................................................................

                 if (dataStr[0].Equals("SCICOM ECIL BARC") && dataStr[7].Equals("GET_STAT") && dataStr[8].Equals("BARC ECIL SCICOM"))
                 {

                     //label1.Visible = true; label2.Visible = true; label3.Visible = true; label4.Visible = true; label5.Visible = true; label6.Visible = true;
                     //txtZoneId.Visible = true; txtUnitId.Visible = true; txtSupplyVtg.Visible = true; txtTemp.Visible = true; txtBatteryStatus.Visible = true;
                     //cbUnitStatus.Visible = true;

                   
                         String responseData = "SCICOM ECIL BARC|Zone003|Server003|127.0.0.1|127.0.0.1|RES_GET_STAT|Active|3.3|56|active|BARC ECIL SCICOM";
                         Console.WriteLine(responseData);
                         //// Process the data sent by the client.

                         byte[] msg = System.Text.Encoding.ASCII.GetBytes(responseData);

                         //// Send back a response.

                         stream.Write(msg, 0, msg.Length);
                         MessageBox.Show("Response send");
                         Console.WriteLine("Sent: {0}", responseData);

                         
                 }
            }

            // Shutdown and end connection
            //client.Close();
        }

    }

    private void btnSend_Click(object sender, EventArgs e)
    {
        
        responseData = "SCICOM ECIL BARC|" + txtZoneId.Text + "|" + txtUnitId.Text + "|" + localAddr +"|127.0.0.1|RES_GET_STAT|" + cbUnitStatus.Text + "|" + txtSupplyVtg.Text + "|" + txtTemp.Text + "|" + txtBatteryStatus.Text + "|BARC ECIL SCICOM";
        Console.WriteLine(responseData);
        // Process the data sent by the client.
      

        byte[] msg = System.Text.Encoding.ASCII.GetBytes(responseData);

        // Send back a response.
       // this.Invoke((MethodInvoker)delegate { stream.Write(msg, 0, msg.Length); });
       stream.Write(msg, 0, msg.Length);
        Console.WriteLine("Sent: {0}", responseData);
Posted
Updated 14-Jun-21 3:50am
v2
Comments
[no name] 14-Jun-21 11:42am    
You need what is known as "error handling". See example.

https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient.getstream?view=net-5.0

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900