So, I’m pretty new to all this network programming, and I have a few questions…
I’m building a client-server chat application, wherein the server is running, the client(s) connect(s) to the server, and then when a client sends a message to the server, the server relays it to all the clients. The server is a console application, and the client is a Windows Form Application.
The error I’m getting is in my client, at the very top of my form, I have a textbox to take in a user’s name and a button to “submit” it and connect to the server with that username.
Anyways, this is my button connect code:
private void btnConnect_Click(object sender, EventArgs e)
{
readData = "Connecting to chat server...";
msg();
try
{
sck_client.Connect("127.0.0.1", 8888);
sw = new StreamWriter(sck_client.GetStream());
string toSend = txtUsername.Text;
sw.Write(toSend);
sw.Flush();
chatThread = new Thread(GetMessages);
chatThread.Start();
}
catch (Exception ex)
{
readData = ex.ToString();
msg();
}
}
msg() quite simply takes the value in readData and prints it to the screen (in a richtextbox). sw is a streamwriter that has been declared publicly, outside of the method, so is sck_client (a TcpClient) and chatThread (a Thread).
Basically, the issue is, when I run my program and try to connect, it throws Exception ex, as though it cannot connect. It throws a NullReferenceException with the text:
System.NullReferenceException: Object reference not set to an instance
of an object. at Chat_Client.Main.btnConnect_Click(Object sender,
EventArgs e) in filepath\Chat_Client\Main.cs:line36
That occurs even when my server is running and listening to port 8888. So, what should I do to fix it?
If you need any more of my code to solve the problem, let me know in a comment and I’ll post it.
To show where the code is instantiated:
public partial class Main : Form // new class for the form itself
{
// all of these are declared outside any method:
TcpClient sck_client = default(TcpClient);
Thread chatThread = default(Thread);
string readData = null;
StreamWriter sw = default(StreamWriter);
StreamReader sr = default(StreamReader);
...
at some point, you will need to give it a value other than
null(thedefaultforTcpClientisnull). Also, you probably don’t need aStreamWriterjust to send astring– I’d look at usingEncoding(to get the bytes; typically UTF8), and a length-prefix of the size (in bytes).