C#TCP通讯使用NetworkStream遇到的问题。尝试读取或写入受保护的内存。这通常指示其他内存已损坏

谭某人不吃鱼 2017-11-21 07:54:33
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace TcpSocketServer
{
public class TYHTcpServer
{
public List<TClient> tClients = new List<TClient>();//客户端列表
private TcpListener tcpListener=null;//声明一个侦听对象
public TYHTcpServer(string ip, int port)
{
tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), port);
tcpListener.Start();
tcpListener.BeginAcceptTcpClient(new AsyncCallback(ClientAccept), tcpListener);//开始尝试客户端连接

}
public void CloseTcp()
{
tcpListener.Stop();
}
private void ClientAccept(IAsyncResult result)
{
TcpListener tcpL = (TcpListener)result.AsyncState;
TcpClient tcpC = tcpL.EndAcceptTcpClient(result);
TClient tClient = new TClient(tcpC, this);
tClients.Add(tClient);
tcpL.BeginAcceptTcpClient(new AsyncCallback(ClientAccept), tcpL);
}
}
public class TClient
{
private TcpClient tcpClient = null;//客户端对象
public string clientIP = "";
public string clientPort = "";
private NetworkStream netWorkStream = null;//数据发送对象
private TYHTcpServer m_Parent = null;//父级类
public TClient(TcpClient tcpC, TYHTcpServer parent)
{
this.tcpClient = tcpC;
this.m_Parent = parent;
string clientIP = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString(); //获取客户端IP
string clientPort = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port.ToString(); //获取客户端端口

SocketServerData.ClientIP = clientIP;
SocketServerData.ClientPort = clientPort;

this.netWorkStream = tcpClient.GetStream();
byte[] data = new byte[1024];
this.netWorkStream.BeginRead(data, 0, 1024, new AsyncCallback(DataRec), data);//此处出现问题
}
private void DataRec(IAsyncResult result)
{
int length = netWorkStream.EndRead(result);
List<byte> data = new List<byte>();
data.AddRange((byte[])result.AsyncState);
byte[] bdata = new byte[1024];
netWorkStream.BeginRead(bdata, 0, bdata .Length , new AsyncCallback(DataRec), bdata);//读取流数据
if (length == 0)
{
m_Parent.tClients.Remove(this);
}
else
{
data.RemoveRange(length, data.Count - length);//处理接收到的数据
IntPtr UI = Win32API.FindWindow("frmTcpServer", "frmTcpServer");
SocketServerData.recData = data;
Win32API.SendMessage(UI, 1994, 0, 0);
}
}
public bool send(byte[] data)
{
netWorkStream.Write(data, 0, data.Length);
return (true);
}
}
}

这是在网上找的一个TCP通讯服务端的实例。测试发现接收数据时报错。请教各位大神是哪里出错了
...全文
162 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

110,561

社区成员

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

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

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