我正在制作客户端 - 服务器应用程序,但是当我尝试登录时会抛出OutOfMemoryException,这是我的代码服务器端:
byte[] buffer = new byte[4];
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
buffer = new byte[4];
int readBytes = networkStream.Read(buffer, 0, 4);
readBytes = networkStream.Read(buffer, 0, 4);
if (readBytes == 0)
break;
int MessageSize = BitConverter.ToInt32(buffer, 0);
byte[] bufferreader = new byte[MessageSize]; <- here the exception is thrown
readBytes = networkStream.Read(bufferreader, 0, MessageSize);
if (readBytes == 0)
break;
dataFromClient = Encoding.ASCII.GetString(bufferreader);
rCount = Convert.ToString(requestCount);
serverResponse = R.Respond(dataFromClient);
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
这是我的客户端代码:
clientSocket.Connect("192.168.1.100", 666);
SHA512Managed S = new SHA512Managed();
byte[] result = S.ComputeHash(Encoding.UTF8.GetBytes(password));
string epassword = Convert.ToBase64String(result);
try
{
byte[] buffer = new byte[4];
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = Encoding.ASCII.GetBytes("authenticate|" + user + "$");
buffer = new byte[4];
buffer = BitConverter.GetBytes(outStream.Length);
serverStream.Write(buffer, 0, 4);
serverStream.Flush();
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = Encoding.ASCII.GetString(inStream);
}
catch(Exception ex)
{
Toast.MakeText(l, ex.Message, ToastLength.Long).Show();
}
Toast.MakeText(l, "Logged In: " + epassword, ToastLength.Long).Show();
所以基本上客户端首先将实际消息的长度发送到服务器,以便它知道它有多少字节,但是当我创建一个新的缓冲区来保存消息时它会抛出OutOfMemoryException,
提前致谢
答案 0 :(得分:1)
问题可能在于您如何阅读包含消息长度的标题:
buffer = new byte[4];
int readBytes = networkStream.Read(buffer, 0, 4);
readBytes = networkStream.Read(buffer, 0, 4);
你在这里做的是从流中读取4个字节到缓冲区,然后再读取4个字节 ,覆盖前一个缓冲区。这与下面的客户端发送代码不匹配,其中头部以前4个字节发送。所以会发生什么是你获得消息大小,用实际有效负载的前4个字节覆盖它,然后尝试根据这4个任意字节分配一个缓冲区。
删除第二个读取电话,它应该没问题。
但是,一般来说,您已经做了很多工作,框架已经可以为您做了。您可以创建一个StreamWriter
来管理您的所有阅读,而不必担心将邮件大小发送为&#34;标题&#34;:
NetworkStream networkStream = clientSocket.GetStream();
StreamReader reader = new StreamReader(networkStream, Encoding.ASCII)
dataFromClient = reader.ReadToEnd();
(当然还有相应的StreamWriter
电话)