C#接受文件

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading;

using System.Threading.Tasks;

namespace Server

{

class Program

{

static void Main(string[] args)

{

IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);

Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

sock.Bind(ip);

sock.Listen(1);

while(true)

{

Socket client = sock.Accept();

if (client.Connected)

{

Thread clientThread = new Thread(new ParameterizedThreadStart(MyClient));

clientThread.IsBackground = true;

clientThread.Start(client);

}

}

}

private const int BUFFERSIZE = 1024/* * 1024*/;

private static string _path = @"D:\";

private static void MyClient(object socket)

{

Socket clientSocket = socket as Socket;

string clientName = clientSocket.RemoteEndPoint.ToString();

Console.WriteLine("新客户端连接:" + clientName);

try

{

while(true)

{

byte[] buffer = new byte[BUFFERSIZE];

int countReceive = clientSocket.Receive(buffer);

string receiveStr = Encoding.Default.GetString(buffer, 0, countReceive);

Console.WriteLine("收到:" + clientName + ":" + receiveStr);

string[] command = receiveStr.Split(',');

string fileName = null;

long fileLength = -1L;

if (command[0] == "nameAndLength")

{

fileName = command[1];

fileLength = long.Parse(command[2]);

clientSocket.Send(Encoding.Default.GetBytes("ok"));

Console.WriteLine("接收文件:" + fileName + " 请等候......");

long recieved = 0L;

using (FileStream fsWriter = new FileStream(Path.Combine(_path,fileName), FileMode.Create, FileAccess.Write, FileShare.None))

{

int recive;

while(recieved < fileLength)

{

recive = clientSocket.Receive(buffer);

fsWriter.Write(buffer, 0, recive);

fsWriter.Flush();

recieved += recive;

Console.WriteLine("已接收数据:{0}/{1}", recieved.ToString(), fileLength.ToString());

}

Console.WriteLine("接收完成......\n");

}

}

}

}

catch (Exception)

{

Console.WriteLine("客户端:" + clientName + "退出");

}

}

}

}

相关推荐
大飞pkz1 小时前
【设计模式】责任链模式
开发语言·设计模式·c#·责任链模式
gplitems1232 小时前
Gunslinger – Gun Store & Hunting WordPress Theme: A Responsible
开发语言·前端·javascript
大飞pkz3 小时前
【设计模式】六大基本原则
开发语言·设计模式·c#·六大原则
iCxhust3 小时前
Intel8259汇编串口接收转C语言
c语言·开发语言·汇编
掘根4 小时前
【Qt】布局管理器
开发语言·qt
半夏知半秋4 小时前
skynet-socket.lua源码分析
服务器·开发语言·学习·架构·lua
西猫雷婶5 小时前
random.shuffle()函数随机打乱数据
开发语言·pytorch·python·学习·算法·线性回归·numpy
来生硬件工程师5 小时前
CH582 GPIO
c语言·开发语言·单片机
椒颜皮皮虾5 小时前
DeploySharp开源发布:让C#部署深度学习模型更加简单
c#·openvino
fly-phantomWing6 小时前
在命令提示符页面中用pip命令行安装Python第三方库的详细步骤
开发语言·python·pip