我的服务器类:
namespace Net_Send_File
{
class Server
{
private TcpListener listener;
private IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 15550);
private bool active;
string arg;
// private Socket xxx;
public Server()
{
Console.Clear();
Console.Title = "Server";
Main();
}
private void Main()
{
listener = new TcpListener(ipep);
try
{
listener.Start();
active = true;
ListenForConnections();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
private void ListenForConnections()
{
Console.Clear();
Console.WriteLine("Listening for connections...");
while (active)
{
TcpClient client = listener.AcceptTcpClient();
Console.BackgroundColor = ConsoleColor.Green;
Console.WriteLine("Connection @ {0}", TCPIP(client));
new Thread(new ParameterizedThreadStart(HandleClientData)).Start(client);
}
}
private void HandleClientData(object _c)
{
TcpClient c = (TcpClient)_c;
string ipaddr = TCPIP(c);
NetworkStream s = c.GetStream();
// I tried this byte[] buffer = new byte[c.ReceiveBufferSize]; It throws an Exeption.
byte[] buffer = new byte[1024];
int bytesRead;
while (active)
{
bytesRead = 0;
try
{
bytesRead = s.Read(buffer, 0, buffer.Length/2);
}
catch (Exception ex)
{
Console.WriteLine("Socket error @ {0}:\r\n{1}", ipaddr, ex.Message);
Console.ReadLine();
break;
}
if (bytesRead == 0)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("Disconnected @ {0}", ipaddr);
//new Thread(new ParameterizedThreadStart.ListenForConnections);
break;
}
string dataStr = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
using (var fs = File.OpenWrite("test.txt"))
{
fs.Write(buffer, 0, buffer.Length);
fs.Close();
}
}
}
private string TCPIP(TcpClient c)
{
return ((IPEndPoint)c.Client.RemoteEndPoint).Address.ToString();
}
};
我的客户类:
class Client
{
private TcpClient client;
// private TcpClient client1;
private IPEndPoint ipep;
private int port;
public Client()
{
Console.Clear();
Console.Title = "Client";
bool error = false;
while (true)
{
Console.WriteLine("IPEndPoint: ");
string input = Console.ReadLine();
if (!input.Contains(':'))
{
Console.WriteLine("IPEndPoint in bad format");
break;
}
string[] s1 = input.Split(':');
IPAddress ipaddr;
if (!IPAddress.TryParse(s1[0], out ipaddr) || !int.TryParse(s1[1], out port))
{
Console.WriteLine("IPEndPoint in bad format");
Console.ReadLine();
error = true;
break;
}
ipep = new IPEndPoint(ipaddr, port);
try
{
client = new TcpClient();
client.Connect(ipep);
Console.WriteLine("client 1 is Ready!");
//client1 = new TcpClient();
//client1.Connect(ipep);
//Console.WriteLine("client 2 is Ready!");
}
catch (Exception ex)
{
Console.WriteLine("Unable to connect\r\nReason: {0}", ex.Message);
Console.ReadLine();
error = true;
}
break;
}
while (!error)
{
Console.Clear();
Console.WriteLine("File path: ");
string filePath = Console.ReadLine();
if (File.Exists(filePath) == false)
{
Console.WriteLine("File does not exist\r\nPress ENTER to try again");
Console.ReadLine();
}
byte[] buffer;
using (var fs = File.OpenRead(filePath))
{
buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
Int64 a = client.SendBufferSize; ;
fs.Close();
}
if (SendData(buffer))
{
// client.SendBufferSize(buffer);
//int a = client.SendBufferSize; ;
Console.WriteLine("File sent\r\nFile size: {0} KB", (buffer.Length / 1024));
//a.SetLength((buffer.Length / 1024));
Console.ReadLine();
}
break;
}
}
private bool SendData(byte[] data)
{
try
{
using (NetworkStream ns = client.GetStream())
{
ns.Write(data, 0, data.Length);
ns.Close();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine("Unable to send file\r\nReason: {0}\r\nDetailed:\r\n{1}", ex.Message, ex.ToString());
Console.ReadLine();
return false;
}
}
}
}
}
首先接受我的道歉,我的代码被严重评论。或者老实说,几乎没有评论。
服务器类,在名为private void HandleClient Data(object _)
的方法下,我有一个缓冲区。缓冲区设置为字节[1024]。我想从客户端接收bufferSize(我的测试文件),将Server buffer =设置为ClientBuffer,然后在接收文件之后。我有一个60MB的测试文件。我试图将缓冲区大小从客户端发送到服务器,但它不能正常工作。有人能告诉我我能做什么以及如何做?
提前致谢
答案 0 :(得分:3)
您应该实现应用程序级协议,例如:
MESSAGE:
[SIZE (8 BYTES)][DATA (SIZE BYTES)]
然后,使用BinaryReader
和BinaryWriter
//client
var writer = new BinaryWriter(client.GetStream());
FileInfo fileInfoToSend = new FileInfo(path);
long fileSize = fileInfoToSend.Length;
writer.Write(fileSize);
using (FileStream fileStream = fileInfoToSend .Open(FileMode.Open, FileAccess.Read))
{
fileStream.CopyTo(writer.BaseStream);
fileStream.Close();
}
//server
var stream = c.GetStream();
var reader = new BinaryReader(c.GetStream());
FileInfo fileInfoToWrite = new FileInfo(path);
long fileSize = reader.ReadInt64();
using (FileStream fileStream = fileInfoToWrite.Create())
{
int read = 0;
for (long i = 0; i < fileSize; i += (long)read)
{
byte[] buffer = new byte[1024];
read = stream.Read(buffer, 0, Math.Min(fileSize - i, 1024));
if (read == 0)
return;//client disconnected!(or throw Exception)
fileStream.Write(buffer, 0, read);
}
}
未测试