C# tcpListener和tcpClient通信问题

scottneal 2019-06-11 05:36:35
我在用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);
}
}

...全文
301 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
jx315425246 2019-06-12
  • 打赏
  • 举报
回复
要有服务端的代码,

while ((i = ns.Read(bytes, 0, bytes.Length))!= 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
s += data;
}
这个代码是只读,没有回复对方,是否只读了一次后,在TcpClient tcpClient = tcpListener.AcceptTcpClient();处卡死
Water Lee 2019-06-11
  • 打赏
  • 举报
回复
另外,我没看到你接收到什么时候结束哦,如果粘包,跳不出循环是有可能的。
Water Lee 2019-06-11
  • 打赏
  • 举报
回复
我觉得你跟我遇到的是同一个问题。你先要考虑以byte数组获取到所有传输的数据,再考虑转为string否则数据会出错,我就遇到了

110,896

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧