0

I am not connected to my server and i type some text in the send text and press send, there will be a warning showing in my program serverStream.Write(outStream, 0, outStream.Length); NullreferenceException is unhandled. is there anyway to prevent this warning from showing?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;

namespace SocketClient
{

    public partial class SocketClient : Form
    {
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        NetworkStream serverStream = default(NetworkStream);
        string readData = null;


        public SocketClient()
        {
            InitializeComponent();
        }


        private void getMessage()
        {
            while (true)
            {
                serverStream = clientSocket.GetStream();
                int buffSize = 0;
                byte[] inStream = new byte[10025];
                buffSize = clientSocket.ReceiveBufferSize;
                serverStream.Read(inStream, 0, buffSize);
                string returndata = System.Text.Encoding.ASCII.GetString(inStream);
                readData = "" + returndata;
                msg();
            }
        }


        private void msg()
        {
            if (this.InvokeRequired)
                this.Invoke(new MethodInvoker(msg));
            else
                textDisplay.Text = textDisplay.Text + Environment.NewLine + " >> " + readData;
        }


        private void buttonConnect_Click(object sender, EventArgs e)
        {
            readData = "Conected to NYP Chat Server ...";
            msg();
            clientSocket.Connect("127.0.0.1", 8888);
            serverStream = clientSocket.GetStream();

            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textName.Text + "$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

            Thread ctThread = new Thread(getMessage);
            ctThread.Start();
        }


        private void buttonSend_Click(object sender, EventArgs e)
        {
            // send text
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textSend.Text + "$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
            //clear textsend textbox
            textSend.Text = "";


        }

        private void textDisplay_TextChanged(object sender, EventArgs e)
        {
            textDisplay.SelectionStart = textDisplay.Text.Length;
            textDisplay.ScrollToCaret();
            textDisplay.Refresh();
        }

        private void textSend_TextChanged(object sender, EventArgs e)
        {
            buttonSend.Enabled = !string.IsNullOrEmpty(textSend.Text);
        }
    }
}
1
  • By the way, there's no point in making a separate returndata variable in getMessage; you can simply write readData = Encoding.ASCII.GetString(inStream);. Commented Dec 18, 2009 at 2:00

6 Answers 6

1

In buttonSend_Click, you need to check that serverStream isn't null, like this:

if (serverStream == null) {
    MessageBox.Show("Please connect to a server.");
    return;
}

By the way, you're setting serverStream an extra time in getMessage; you shouldn't.

Sign up to request clarification or add additional context in comments.

3 Comments

under private void buttonSend_Click(object sender, EventArgs e)
after i add in the code, although the error is clear, but i have a problem my msg cannot be send over
I think you should still be using a try / catch / finally like i showed u below. there are other errors that will potentially throw exceptions in that method. checking if the obj is null is literally a crutch.
0

Maybe you need to initialize the ServerStream instead of writing NetworkStream serverStream = default(NetworkStream);

For example, you would have to initialize in this manner:

myNetworkStream = new NetworkStream(mySocket);     

Comments

0
private void buttonSend_Click(object sender, EventArgs e){
    try{
    // send text
        byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textSend.Text + "$");
        serverStream.Write(outStream, 0, outStream.Length);
        serverStream.Flush();
        //clear textsend textbox
        textSend.Text = "";


    }
    catch(Exception ex){

    // handle error here
    }
    finally {
    // clean up
    }
}

Comments

0

i havnt played with this too much. but if you arent connected, serverStream = clientSocket.GetStream(); might set serverStream to nothing, if it cant "get the stream" Try checking if serverStream is null before serverStream.Write is called. or you can encapsulate all things dependant on serverStream NOT being null in a try/catch/finally.

Comments

0

Make sure the NetworkStream object is not null before sending. Tho you should probably display a MessageBox to the user.

private void buttonSend_Click(object sender, EventArgs e)
{
    if(serverStream == null)
        return;

    // send text
    byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textSend.Text + "$");
    serverStream.Write(outStream, 0, outStream.Length);
    serverStream.Flush();
    //clear textsend textbox
    textSend.Text = "";
}

Comments

0

The problem isn't just that you're getting the null reference - the real problem is that you're attempting to do something you're not in a valid state to do.

If you aren't connected, all of the functionality associated with 'being connected' should be flat out disabled. Ideally, disable the controls until you detect you're in a connected state.

What I'd be more likely to do is extract the actual logic from your form class, and when you call any methods dealing with the network, throw your own exception if you're not connected.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.