我試圖使用套接字將消息發送到電腦進行初始化,但我不斷收到此錯誤:的StreamWriter爲空,即使它在C#
System.NullReferenceException: 'Object reference not set to an instance of an object.'
sw was null.
這是我的代碼:
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);
}
這是按鈕的代碼:
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);
}
的代碼的WriteLine在連接方法的作品,但在t時的代碼他發送方法沒有。我試過這個問題:What is a NullPointerException, and how do I fix it?但它沒有幫助我。 感謝
告訴你如何調用'send'和'connect'。並且,你調試了嗎?.. –
如果你真的不能追蹤其他問題和答案的空指針,你需要提供一個[mcve]。只是向我們展示了兩個片段,並向我們保證該程序的結構正確以確保沒有空值是不夠的(尤其是因爲,如果情況如此,則不會有空引用 - 顯然,您的假設目前不正確) –
你在哪裏叫'發送'? –