代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Net.Sockets;
using System.IO;
namespace TestSocketServerHSTF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//不显示出dataGridView1的最后一行空白
dataGridView1.AllowUserToAddRows = false;
}
#region 定义变量
#endregion
#region 进入窗体即启动服务
private void Form1_Load(object sender, EventArgs e)
{
//开启接收线程
Thread TempThread = new Thread(new ThreadStart(this.StartReceive));
TempThread.Start();
}
#endregion
#region 功能函数
private void StartReceive()
{
//创建一个网络端点
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, int.Parse("2005"));
//MessageBox.Show(IPAddress.Any);
//创建一个套接字
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定套接字到端口
server.Bind(ipep);
//开始侦听(并堵塞该线程)
server.Listen(10);
//确认连接
Socket client = server.Accept();
//获得客户端节点对象
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
//获得[文件名]
string SendFileName = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
//MessageBox.Show("文件名" + SendFileName);
//获得[包的大小]
string bagSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
//MessageBox.Show("包大小" + bagSize);
//获得[包的总数量]
int bagCount = int.Parse(System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)));
//MessageBox.Show("包的总数量" + bagCount);
//获得[最后一个包的大小]
string bagLast = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
//MessageBox.Show("最后一个包的大小" + bagLast);
//创建一个新文件
FileStream MyFileStream = new FileStream(SendFileName, FileMode.Create, FileAccess.Write);
//已发送包的个数
int SendedCount = 0;
while (true)
{
byte[] data = TransferFiles.ReceiveVarData(client);
if (data.Length == 0)
{
break;
}
else
{
SendedCount++;
//将接收到的数据包写入到文件流对象
MyFileStream.Write(data, 0, data.Length);
//显示已发送包的个数
//MessageBox.Show("已发送包个数"+SendedCount.ToString());
}
}
//关闭文件流
MyFileStream.Close();
//关闭套接字
client.Close();
//填加到dgv里
//文件大小,IP,已发送包的个数,文件名,包的总量,最后一个包的大小
this.dataGridView1.Rows.Add(bagSize, clientep.Address, SendedCount, SendFileName, bagCount, bagLast);
//MessageBox.Show("文件接收完毕!");
}
#endregion
#region 拦截Windows消息,关闭窗体时执行
protected override void WndProc(ref Message m)
{
const int WM_SYSCOMMAND = 0x0112;
const int SC_CLOSE = 0xF060;
if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
{//捕捉关闭窗体消息
// User clicked close button
//this.WindowState = FormWindowState.Minimized;//把右上角红叉关闭按钮变最小化
ServiceStop();
}
base.WndProc(ref m);
}
#endregion
#region 停止服务
//停止服务
private void ServiceStop()
{
try
{
}
catch { }
try
{
}
catch { }
}
#endregion
}
}
联系客服