我正在读取大约3824726字节的大字节。我已经尝试了很多函数来读取整个字节。它正好读取3816534个字节,而while循环正在消失一些地方。剩余的8192个字节未被读取,也没有异常。它读到正好是3816534然后当打开时while循环消失了。请一些人帮忙,告诉我这里可能存在什么问题。我已经尝试了很多但是同样的事情发生在不同的功能中。
public static void ReadFully(NetworkStream stream, int initialLength)
{
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int chunk;
try
{
int read = -1;
int totread = 0;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
totread += read;
Console.WriteLine("Toatal Read" + totread);
string filePath = "C:\\Foo.txt";
StreamWriter objWriter;
using (objWriter = File.AppendText(filePath))
{
objWriter.WriteLine(totread);
objWriter.Flush();
objWriter.Close();
}
}
Console.WriteLine("Toatal Read" + totread);
}
catch (Exception ex)
{ throw ex; }
}
客户端将字节发送到服务器
byte[] fileA;
IPAddress ipAd = IPAddress.Parse("IpAddress");
TcpClient client = new TcpClient(ipAd.ToString(), Port);
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader("D:/Users/Public/Pictures/Sample Pictures/06250_2.jpg");
//StreamReader reader = new StreamReader("D:/Users/703132799/Desktop/Foo.txt");
string data = reader.ReadToEnd();
reader.Close();
fileA = System.Text.Encoding.ASCII.GetBytes(data);
int length = 0;
length = fileA.Length;
Console.WriteLine("Sending Buffer Length-" + length);
stream.Write(fileA, 0, fileA.Length);
stream.Flush();
//Thread.Sleep(10000);
Console.ReadLine();
服务器上的整个代码,它是异步方式
static void Main(string[] args)
{
StartServer();
}
private static TcpListener _listener;
public static void StartServer()
{
IPAddress localIPAddress = IPAddress.Parse("IPAddress");
IPEndPoint ipLocal = new IPEndPoint(localIPAddress, Port);
_listener = new TcpListener(ipLocal);
_listener.Start();
WaitForClientConnect();
}
private static void WaitForClientConnect()
{
object obj = new object();
_listener.BeginAcceptTcpClient(new System.AsyncCallback(OnClientConnect), obj);
Console.ReadLine();
}
private static void OnClientConnect(IAsyncResult asyn)
{
try
{
TcpClient clientSocket = default(TcpClient);
clientSocket = _listener.EndAcceptTcpClient(asyn);
HandleClientRequest clientReq = new HandleClientRequest(clientSocket);
clientReq.StartClient();
}
catch (Exception ex)
{
throw ex;
}
WaitForClientConnect();
}
}
public class HandleClientRequest
{
TcpClient _clientSocket;
NetworkStream _networkStream = null;
public HandleClientRequest(TcpClient clientConnected)
{
this._clientSocket = clientConnected;
}
public void StartClient()
{
_networkStream = _clientSocket.GetStream();
WaitForRequest();
}
public void WaitForRequest()
{
byte[] buffer = new byte[_clientSocket.ReceiveBufferSize];
_networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
}
private void ReadCallback(IAsyncResult result)
{
string sRecMsgAsciiWithHex = string.Empty;
NetworkStream networkStream = _clientSocket.GetStream();
ReadFully(networkStream, 65536);
}
public static void ReadFully(NetworkStream stream, int initialLength)
{
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int chunk;
try
{
int read = -1;
int totread = 0;
using (var fileStream = File.OpenWrite("C:\\Foo.txt"))
{
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
totread += read;
Console.WriteLine("Toatal Read" + totread);
fileStream.Write(buffer, 0, buffer.Length);
//string filePath = "C:\\Foo.txt";
//StreamWriter objWriter;
//using (objWriter = File.AppendText(filePath))
//{
// objWriter.WriteLine(totread);
// objWriter.Flush();
// objWriter.Close();
//}
}
}
Console.WriteLine("Toatal Read" + totread);
}
catch (IOException e)
{ throw; }
}
答案 0 :(得分:0)
<强>更新强>
你没有关闭连接 - 这很简单;如果您有兴趣,我可以发布完整的代码示例。
将client.Close();
放在stream.Flush()
“客户端发送字节到服务器”例程的末尾。
所有代码:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
StartServer();
// test sending
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(IPAddress.Parse("127.0.0.1"), 4000);
// get a file here instead
byte[] longBuffer = new byte[3824726];
byte[] buffer = new byte[4096];
// emulated stream over emulated buffer
using (var stream = new MemoryStream(longBuffer, false)) {
while (true) {
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0) {
break;
}
for (int sendBytes = 0; sendBytes < read; sendBytes += client.Send(buffer, sendBytes, read - sendBytes, SocketFlags.None)) {
}
}
}
// the tricky part ;)
client.Close();
Console.In.ReadLine();
_stop = true;
}
private static TcpListener _listener;
private static volatile bool _stop = false;
private sealed class Client : IDisposable {
public Socket Socket { get; private set; }
public byte[] Buffer { get; private set; }
public FileStream WriteStream { get; private set; }
public Client(Socket socket) {
if (socket == null) {
throw new ArgumentNullException("socket");
}
Socket = socket;
Buffer = new byte[4096];
WriteStream = File.OpenWrite(@"c:\foo" + Guid.NewGuid().ToString("N") + ".txt");
}
public void Close() {
if (Socket != null) {
Socket.Close();
}
if (WriteStream != null) {
WriteStream.Close();
}
}
public void Dispose() {
Close();
}
}
public static void StartServer() {
IPAddress localIPAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint ipLocal = new IPEndPoint(localIPAddress, 4000);
_listener = new TcpListener(ipLocal);
_listener.Start();
_listener.BeginAcceptSocket(BeginAcceptSocketCallback, null);
}
private static void BeginAcceptSocketCallback(IAsyncResult asyn) {
Client client = null;
try {
client = new Client(_listener.EndAcceptSocket(asyn));
client.Socket.BeginReceive(client.Buffer, 0, client.Buffer.Length, SocketFlags.None, BeginReceiveCallback, client);
} catch (ObjectDisposedException e) {
HandleSocketFailure(client, e, "BeginAcceptSocketCallback failure", false);
} catch (SocketException e) {
HandleSocketFailure(client, e, "BeginAcceptSocketCallback failure", false);
} catch (Exception e) {
HandleSocketFailure(client, e, "BeginAcceptSocketCallback failure", true);
}
if (!_stop) {
_listener.BeginAcceptSocket(BeginAcceptSocketCallback, null);
}
}
private static void BeginReceiveCallback(IAsyncResult result) {
var client = (Client)result.AsyncState;
try {
int bytesRead = client.Socket.EndReceive(result);
if (bytesRead > 0) {
client.WriteStream.Write(client.Buffer, 0, bytesRead);
client.Socket.BeginReceive(client.Buffer, 0, client.Buffer.Length, SocketFlags.None, BeginReceiveCallback, client);
} else {
client.Close();
}
} catch (SocketException e) {
HandleSocketFailure(client, e, "BeginReceiveCallback failure", false);
} catch (ObjectDisposedException e) {
HandleSocketFailure(client, e, "BeginReceiveCallback failure", false);
} catch (Exception e) {
HandleSocketFailure(client, e, "BeginReceiveCallback failure", true);
}
}
private static void HandleSocketFailure(Client client, Exception exception, string message, bool isFatal) {
// log exception as well at least for isFatal = true
if (client != null) {
client.Close();
}
}
}
}