我不太确定代码会发生什么。我有一个程序可以读入输入(来自本地主机上的telnet客户端)并将其存储到字典中。此输入按需存储;
然而,当没有"围绕输入的第二部分;PersonsName"位于"
PersonName位于位置
我收到此错误; System.IO.IOException:无法从传输连接读取数据:远程主机强制关闭现有连接。 ---> System.Net.Sockets.SocketException:远程主机强制关闭现有连接 在System.Net.Sockets.Socket.Receive(Byte []缓冲区,Int32偏移量,Int32大小,SocketFlags socketFlags) 在System.Net.Sockets.NetworkStream.Read(Byte []缓冲区,Int32偏移量,Int32大小) ---内部异常堆栈跟踪结束--- 在System.Net.Sockets.NetworkStream.Read(Byte []缓冲区,Int32偏移量,Int32大小) 在System.IO.StreamReader.ReadBuffer() 在System.IO.StreamReader.ReadLine() 位于C:\ Users \ UserPC \ source \ repos \ locationserver \ locationserver \ Program.cs中的locationserver.Program.doRequest(NetworkStream socketStream):第61行
我的代码如下
public static Dictionary<string, string> dataBase;
static void Main(string[] args)
{
//create a database then populate it with an item so its not null
dataBase = new Dictionary<string, string>();
dataBase.Add("Person", "in Location");
runServer();
}
static void runServer()
{
TcpListener listener;
Socket connection;
NetworkStream socketStream;
try
{
listener = new TcpListener(IPAddress.Any, 43);
listener.Start();
Console.WriteLine("Server has now started");
while (true)
{
connection = listener.AcceptSocket();
socketStream = new NetworkStream(connection);
Console.WriteLine("A connection has been made");
doRequest(socketStream);
socketStream.Close();
connection.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void doRequest(NetworkStream socketStream)
{
try
{
//set timeout value to 1 second
socketStream.ReadTimeout = 1000;
socketStream.WriteTimeout = 1000;
StreamWriter sw = new StreamWriter(socketStream);
StreamReader sr = new StreamReader(socketStream);
string line = sr.ReadLine().Trim();
//A load of code it never goes into
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
已经过了一段时间并且不知道发生了什么。任何帮助都会很棒。谢谢
编辑:发生错误的行如下
string line = sr.ReadLine().Trim();