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 byteBUFFERSIZE;

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 (command0 == "nameAndLength")

{

fileName = command1;

fileLength = long.Parse(command2);

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 + "退出");

}

}

}

}

相关推荐
西门吹-禅7 小时前
java springboot N+1问题
java·开发语言·spring boot
skywalk81637 小时前
设计并实现段言的 C FFI 绑定机制 @Trae
c语言·开发语言·python·编程
IT笔记9 小时前
【Rust】Rust Match 模式匹配详解
java·开发语言·rust
2zcode9 小时前
免费开源项目文档:基于MATLAB卷积神经网络的口罩佩戴检测系统
开发语言·matlab·cnn
逝水无殇9 小时前
C# 运算符重载详解
开发语言·后端·c#
TPBoreas10 小时前
配置信息防泄露方案:.env 环境隔离详解(dotenv-java)
java·开发语言
敲代码的嘎仔10 小时前
实习日志day6--实习日志day6--title命名规范化&businessType纠正&补充缺失的@Log注解&报警与通信模块补充&产出阶段总结文档
java·开发语言·人工智能·git·python·实习·大二
江华森10 小时前
Python 实现高德地图找房(一):环境搭建与数据爬虫
开发语言·爬虫·python
杜子不疼.10 小时前
【Qt初识】信号槽(三):机制意义、断开连接与 Lambda 表达式
开发语言·数据库·qt
老迟到的茉莉12 小时前
Hermes 是谁?跟 Claude Code 差在哪
开发语言·python