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

}

}

}

}

相关推荐
wjs2024几秒前
DOM CDATA
开发语言
Tingjct2 分钟前
【初阶数据结构-二叉树】
c语言·开发语言·数据结构·算法
猷咪28 分钟前
C++基础
开发语言·c++
IT·小灰灰29 分钟前
30行PHP,利用硅基流动API,网页客服瞬间上线
开发语言·人工智能·aigc·php
快点好好学习吧31 分钟前
phpize 依赖 php-config 获取 PHP 信息的庖丁解牛
android·开发语言·php
秦老师Q32 分钟前
php入门教程(超详细,一篇就够了!!!)
开发语言·mysql·php·db
烟锁池塘柳032 分钟前
解决Google Scholar “We‘re sorry... but your computer or network may be sending automated queries.”的问题
开发语言
是誰萆微了承諾32 分钟前
php 对接deepseek
android·开发语言·php
2601_9498683636 分钟前
Flutter for OpenHarmony 电子合同签署App实战 - 已签合同实现
java·开发语言·flutter
星火开发设计1 小时前
类型别名 typedef:让复杂类型更简洁
开发语言·c++·学习·算法·函数·知识