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

}

}

}

}

相关推荐
YMWM_18 分钟前
查看realsense相机序列号脚本
开发语言·python·数码相机
传奇开心果编程39 分钟前
【dioxus0.7基础语法学与练】第8课:RSX 宏 — Dioxus 声明式 UI 语法
开发语言·学习·rust
wuyk5551 小时前
18.Kruskal 算法:用最短的边连成一张网
开发语言·算法·图论
Evand J1 小时前
【MATLAB例程,图像降噪7】高斯加权滑动窗口滤波,用于图像降噪,带质量评价,附代码下载链接
开发语言·图像处理·matlab·滑动窗口·滤波·降噪·图像滤波
十年一梦惊觉醒1 小时前
快手视频发布助手,全自动视频发布带货工具
开发语言·前端·javascript
Java后端的Ai之路1 小时前
一文搞懂 GitHub Actions-CICD
开发语言·大模型·github·cicd·action
码匠许师傅1 小时前
【C++三方组件】开篇总论:为什么需要以及如何选型?
开发语言·c++
cvby2 小时前
C++11--右值引用和移动语义
开发语言·c++
en.en..2 小时前
TCP/UDP 收发流程(网络字节序---函数讲解)
开发语言·php
名字还没想好☜2 小时前
Go 用 json.Decoder 流式解析大 JSON:边读边处理不爆内存
开发语言·后端·golang·go·json