I am trying to use sockets to send messages to computers, but I keep getting this error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
sw was null.
This is my code:
public partial class ServerGUI : Form
{
Socket soc;
StreamReader sr;
StreamWriter sw;
Stream s;
public ServerGUI()
{
InitializeComponent();
try
{
if (Server.port == 0)
{ }
else
{
textBox2.Text = Server.port.ToString();
}
}
catch (Exception) { }
}
private void button1_Click(object sender, EventArgs e)
{
connect();
}
void connect()
{
Server.port = int.Parse(textBox2.Text);
TcpListener listener = new TcpListener(IPAddress.Any, Server.port);
listener.Start();
soc = listener.AcceptSocket();
s = new NetworkStream(soc);
sr = new StreamReader(s);
sw = new StreamWriter(s);
sw.AutoFlush = true; // enable automatic flushing
if (soc.Connected == true)
{
Console.WriteLine("Connected");
sw.WriteLine("Server Connected");
}
this.Hide();
Menu menu = new Menu();
menu.Show();
}
void recieve()
{
Console.WriteLine(sr.ReadLine());
}
public void close()
{
s.Close();
soc.Disconnect(true);
Menu menu = new Menu();
menu.Close();
this.Show();
}
public void send(string msg)
{
sw.WriteLine(msg);
}
This is the code for the button:
ServerGUI sgui = new ServerGUI();
public Menu()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
sgui.close();
}
private void button2_Click(object sender, EventArgs e)
{
sgui.send(textBox1.Text);
}
The writeline code in the connect method works but the code in the send method doesn't. I have tried this question: What is a NullPointerException, and how do I fix it? but it has not helped me. Thanks