using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CA.TCP
{
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Configuration;
class Program
{
static void Main(string[] args)
{
var ttt = new byte[100];
Console.WriteLine("1.client");
Console.WriteLine("2.server");
var c = Console.ReadKey();
if (c.KeyChar == '1')
{
Client();
}
else
{
Server();
}
Console.WriteLine("结束");
Console.ReadKey();
}
private static void Server()
{
var port = ConfigurationManager.AppSettings["localIPPoint"];
Console.WriteLine($"监听端口:" + port);
var end = new IPEndPoint(IPAddress.Parse("0.0.0.0"), int.Parse(port));
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(end);
socket.Listen(10);
Console.WriteLine("服务器开始监听");
socket.Blocking = true;
Thread thread = new Thread(AcceptInfo);
thread.IsBackground = true;
thread.Start(socket);
while (true)
{
Thread.Sleep(200);
if (Console.KeyAvailable)
{
var k = Console.ReadKey();
if (k.Key == ConsoleKey.Enter)
{
Console.WriteLine("发送");
byte[] buffer = Encoding.Default.GetBytes(Console.ReadLine());
// client.Send(buffer);
if (dic.Any())
{
dic.FirstOrDefault().Value.Send(buffer);
}
}
}
}
}
//记录通信用的Socket
static Dictionary<string, Socket> dic = new Dictionary<string, Socket>();
static void AcceptInfo(object o)
{
Socket socket = o as Socket;
while (true)
{
//通信用socket
try
{
Console.WriteLine("等待接收");
//创建通信用的Socket
Socket tSocket = socket.Accept();
Console.WriteLine("收到连接");
string point = tSocket.RemoteEndPoint.ToString();
//IPEndPoint endPoint = (IPEndPoint)client.RemoteEndPoint;
//string me = Dns.GetHostName();//得到本机名称
//MessageBox.Show(me);
Console.WriteLine(point + "连接成功!");
//Console.WriteLine(point);
dic.Add(point, tSocket);
//接收消息
Thread th = new Thread(ReceiveMsg);
th.IsBackground = true;
th.Start(tSocket);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
}
}
//接收消息
static void ReceiveMsg(object o)
{
Socket client = o as Socket;
while (true)
{
//接收客户端发送过来的数据
try
{
//定义byte数组存放从客户端接收过来的数据
byte[] buffer = new byte[1024 * 100];
//将接收过来的数据放到buffer中,并返回实际接受数据的长度
int n = client.Receive(buffer);
//将字节转换成字符串
string words = Encoding.Default.GetString(buffer, 0, n).Trim();
if (words.StartsWith("##101."))
{
Console.WriteLine("收到文件上传请求");
var path = AppDomain.CurrentDomain.BaseDirectory + words.Substring(words.IndexOf(".") + 1);
if (System.IO.File.Exists(path) == false)
{
dic.FirstOrDefault().Value.Send(Encoding.Default.GetBytes("ok"));
Thread.Sleep(100);
dic.FirstOrDefault().Value.Send(Encoding.Default.GetBytes("ok"));
Console.WriteLine("已同意");
int size = 1024 * 1024;
using (var fs = System.IO.File.Create(path))
{
int i = 1;
while (true)
{
var oneSendBuffer = new byte[size];
int length = client.Receive(oneSendBuffer);
if (Encoding.Default.GetString(oneSendBuffer).Trim('\0') == "end")
{
break;
}
fs.Write(oneSendBuffer, 0, length);
fs.Flush();
Console.WriteLine(i++);
}
dic.FirstOrDefault().Value.Send(Encoding.Default.GetBytes("上传完成"));
Console.WriteLine("上传完成");
}
}
else
{
dic.FirstOrDefault().Value.Send(Encoding.Default.GetBytes("文件已存在"));
Console.WriteLine("文件已存在,拒绝上传");
}
}
Console.WriteLine(client.RemoteEndPoint.ToString() + ":" + words);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
}
}
private static void Client()
{
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var ipStr = ConfigurationManager.AppSettings["targetIP"];
Console.WriteLine($"目标IP:{ipStr}");
IPAddress ip = IPAddress.Parse(ipStr);
var port = ConfigurationManager.AppSettings["targetIPPoint"];
Console.WriteLine($"目标端口:{port}");
IPEndPoint endPoint = new IPEndPoint(ip, int.Parse(port));
try
{
while (client.Connected == false)
{
Thread.Sleep(200);
client.Connect(endPoint);
}
byte[] tmp = new byte[1];
client.Blocking = false;
client.Send(tmp, 0, 0);
Console.WriteLine("Connected!");
Console.WriteLine("本地:" + client.LocalEndPoint.ToString());
Console.WriteLine("连接到:" + client.RemoteEndPoint.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
client.Blocking = true;
bool autoReceiving = true;
Thread th = new Thread((s) =>
{
while (true)
{
Thread.Sleep(500);
if (!autoReceiving)
{
continue;
}
try
{
byte[] buff = new byte[1024 * 100];
int n = (s as Socket).Receive(buff);
string str = Encoding.Default.GetString(buff).Trim('\0');
Console.WriteLine("回复:" + str);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
}
});
th.IsBackground = true;
th.Start(client);
while (true)
{
Thread.Sleep(100);
if (Console.KeyAvailable)
{
var k = Console.ReadKey();
if (k.Key == ConsoleKey.Enter)
{
Console.WriteLine("发送");
var str = Console.ReadLine();
if (str.Contains(".") && System.IO.File.Exists(str))
{
var fs = new System.IO.FileInfo(str);
Console.WriteLine("请求发送文件……");
Console.WriteLine($"文件大小:{(fs.Length / 1024.0 / 1024.0).ToString("f2")} MB");
//每次发送大小
int size = 1024 * 1024;
var oneSendBuffer = new byte[size];
Console.WriteLine($"每次发送大小{1}MB");
//需要发送多少次
int sendNum = fs.Length > size ? (int)Math.Ceiling(fs.Length / ((double)size)) : 1;
Console.WriteLine($"需要发送{sendNum}次");
Console.WriteLine();
//停止自动接收消息
autoReceiving = false;
//发送文件请求指令
client.Send(Encoding.Default.GetBytes("##101." + System.IO.Path.GetFileName(str)));
//获取回复
byte[] resultBuffer = new byte[1024];
client.Receive(resultBuffer);
var resultStr = Encoding.Default.GetString(resultBuffer).Trim('\0');
//同意发送
if (resultStr == "ok")
{
Console.WriteLine($"开始发送文件:{DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss")}");
int offset = 0;
using (var stream = fs.OpenRead())
{
//stream.Seek(0, System.IO.SeekOrigin.Begin);
var top = Console.CursorTop + 1;
for (int i = 1; i <= sendNum; i++)
{
offset = stream.Read(oneSendBuffer, 0, oneSendBuffer.Length);
if (offset < size)
{
var temp = new byte[offset];
for (int j = 0; j < offset; j++)
{
temp[j] = oneSendBuffer[j];
}
client.Send(temp);
}
else
{
client.Send(oneSendBuffer);
}
Array.Clear(oneSendBuffer, 0, oneSendBuffer.Length);
Console.SetCursorPosition(0, top);
Console.WriteLine($"{((float)i / sendNum * 100).ToString("f4")}%");
}
}
//避免粘包
Thread.Sleep(500);
client.Send(Encoding.Default.GetBytes("end"));
Console.WriteLine($"发送完成:{DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss")}");
autoReceiving = true;
}
else
{
Console.WriteLine("被拒绝" + resultStr);
}
autoReceiving = true;
}
else
{
byte[] buffer = Encoding.Default.GetBytes(str);
client.Send(buffer);
}
}
}
}
}
}
}