[英]How to fix following basic TCP IP Server code
当服务器通过按钮启动时,下面的代码在名为 Runner 的函数中给出了 SystemNullReferenceException 错误。 我的一位朋友说代码在他的电脑上运行,但我无法让它在我的电脑上运行。 当我通过可执行文件启动代码时,它进入无响应状态,我需要通过杀死程序从任务管理器中关闭它。 从文本框中,IP 读取为 127.0.0.1,端口为 13000。感谢您的指导。
namespace FakeDataTCP_Server_NameSpace
{
public partial class FakeDataTCP_ServerForm : Form
{
public FakeDataTCP_ServerForm()
{
InitializeComponent();
}
private void buttonServerRUN_Click(object sender, EventArgs e)
{
textBoxSTATUS.Clear();
IPAddress sunucuIP = IPAddress.Parse(comboBoxServerIP.Text);
int sunucuPORT = Int32.Parse(textBoxServerPORT.Text);
textBoxSTATUS.AppendText("sunucu IP: " + sunucuIP.ToString() + "\r\n");
textBoxSTATUS.AppendText("PORT: " + sunucuPORT.ToString() + "\r\n");
Socket sunucuSoketListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint sunucuEndIP = new IPEndPoint(sunucuIP, sunucuPORT);
sunucuSoketListener.Bind(sunucuEndIP);
sunucuSoketListener.Listen(100);
textBoxSTATUS.AppendText("Server Started (Listening) \r\n");
Socket istemciSoketi = default(Socket);
FakeDataTCP_ServerForm p = new FakeDataTCP_ServerForm();
Thread sunucuThread = new Thread(new ThreadStart(() => p.Runner(istemciSoketi)));
sunucuThread.Start();
int istemciSAYISI = 0;
while (true)
{
istemciSAYISI++;
istemciSoketi = sunucuSoketListener.Accept();
textBoxSTATUS.AppendText(istemciSAYISI + " clients connected \r\n");
}
}
public void Runner(Socket istci)
{
try
{
while (true)
{
byte[] msg = new byte[1024];
int ebat = istci.Receive(msg);
istci.Send(msg, 0, ebat, SocketFlags.None);
}
}
catch
{
MessageBox.Show("failed");
}
}
}
}
在名为 Runner 的函数中给出 SystemNullReferenceException 错误。
查看这个函数,除了作为参数传递的istci
Socket 之外,我看不到任何内部本身可能是null
的东西。
从那里向后工作,我看到该函数的调用如下:
p.Runner(istemciSoketi)
并且进一步向后工作,我看到istemciSoketi
变量的定义如下:
Socket istemciSoketi = default(Socket);
啊哈! default(Socket)
是null
,所以istemciSoketi
还没有值! 您尝试使用的 Socket 从未真正创建过。 您稍后会分配一个值:
istemciSoketi = sunucuSoketListener.Accept();
...但这直到调用p.Runner()
之后才会发生。
要解决此问题,请将调用p.Runner()
的代码移至 SocketListener 接受连接之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.