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

}

}

}

}

相关推荐
Micro麦可乐6 分钟前
Java常用加密算法详解与实战代码 - 附可直接运行的测试示例
java·开发语言·加密算法·aes加解密·rsa加解密·hash算法
天下一般11 分钟前
go入门 - day1 - 环境搭建
开发语言·后端·golang
雷羿 LexChien21 分钟前
C++内存泄漏排查
开发语言·c++
小码编匠27 分钟前
WPF 自定义TextBox带水印控件,可设置圆角
后端·c#·.net
水果里面有苹果29 分钟前
17-C#的socket通信TCP-1
开发语言·tcp/ip·c#
手握风云-30 分钟前
JavaEE初阶第七期:解锁多线程,从 “单车道” 到 “高速公路” 的编程升级(五)
java·开发语言
nightunderblackcat32 分钟前
进阶向:Python音频录制与分析系统详解,从原理到实践
开发语言·python·音视频
努力学习的小廉1 小时前
深入了解linux系统—— System V之消息队列和信号量
android·linux·开发语言
teeeeeeemo2 小时前
http和https的区别
开发语言·网络·笔记·网络协议·http·https
wuxuanok2 小时前
Web后端开发-Mybatis
java·开发语言·笔记·学习·mybatis