C# tcpListener和tcpClient通信问题
我在用tcpClient和tcpListener写一个简单的聊天软件。我用C#文档中这两个类实现客户端和服务端交流的示例代码的话能正常运行,服务器端部分代码如下:
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
data = null;
NetworkStream ns = tcpClient.GetStream();
int i;
while ((i = ns.Read(bytes, 0, bytes.Length))!= 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
ns.Write(msg, 0, msg.Length);
}
现在我改成新定义一个字符串存储所有的data,循环结束后然后分离出字符串中包含的账号密码等信息,进行数据库查询等操作,再发送结果给客户端。但程序运行后半天没有反应,程序无响应,请问到底哪里出错了。我不太懂计算机网络,是因为我加了太多操作连接早就断开了吗?
while ((i = ns.Read(bytes, 0, bytes.Length))!= 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
s += data;
}
StringReader stringReader = new StringReader(s);
string ss = stringReader.ReadLine();
if (ss.Equals("Login"))
{
string Account, Password;
Account = stringReader.ReadLine();
Password = stringReader.ReadLine();
if (UserLogin(Account, Password))
{
byte[] msg = System.Text.Encoding.ASCII.GetBytes("success");
ns.Write(msg, 0, msg.Length);
}
else
{
byte[] msg = System.Text.Encoding.ASCII.GetBytes("fail");
ns.Write(msg, 0, msg.Length);
}
}