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

}

}

}

}

相关推荐
2601_966949651 天前
如何根据研究的起止时间截取分钟级行情?Python 实战与 QuantDash 数据处理指南
开发语言·python·pandas·量化交易·1024程序员节·股票数据·quantdash
晨曦中的暮雨1 天前
限流算法——固定窗口、滑动窗口、漏桶、令牌桶
java·开发语言·算法
喵了几个咪1 天前
GoWind CMS 拆解:在 Go 里给 TipTap 搭一套 Yjs 协同后端
开发语言·后端·golang
程序员清风1 天前
数据处理脚本工程化:日志、配置、命令行与测试
服务器·开发语言·数据库
淡海水1 天前
07-02-源码-.NET Core GC分配路径
算法·unity·c#·.netcore·gc·1024程序员节
2601_962885721 天前
如何用 Python 把 K 线重采样成任意周期?
开发语言·python
Wang's Blog1 天前
Java 项目实战: 交友项目 - 圈子功能实现:总结
java·开发语言·交友
下一站春风里1 天前
位运算完整学习笔记:按位与(&)+ 异或(^)
开发语言·c++·算法
吴可可1231 天前
C#调用摄像头拍照的三种API方案
c#
天外飞雨道沧桑1 天前
我在浏览器里练了一个 792 参数的大模型,它学会了补全 JavaScript
开发语言·javascript·ai·ecmascript·ai编程