作者:塞上秋雪_838 | 来源:互联网 | 2024-11-25 20:10
// 文件发送按钮点击事件处理
private void btn_sendFile_Click(object sender, EventArgs e)
{
// 打开文件选择对话框
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
// 创建用于发送的Socket对象,指定使用IPv4地址族、流式套接字及TCP协议
Socket socketSent = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 设置目标服务器的IP地址和端口号
IPEndPoint ipSent = new IPEndPoint(IPAddress.Parse(ip), 8001);
// 连接到服务器
ClassSocket socketCOnnet= new ClassSocket(socketSent, ipSent);
Thread tCOnnection= new Thread(new ThreadStart(socketConnet.SocketConnect));
tConnection.Start();
Thread.Sleep(100); // 短暂等待连接建立
// 准备发送文件,并添加特定标识符
ClassSentFile sentFile = new ClassSentFile(dlg, socketSent);
Thread tSentFile = new Thread(new ThreadStart(sentFile.SentFile));
tSentFile.Start();
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
namespace Message
{
class ClassSentFile
{
private OpenFileDialog dlg;
private Socket socketSent;
public ClassSentFile(OpenFileDialog dlg, Socket socketSent)
{
this.dlg = dlg;
this.socketSent = socketSent;
}
public void SentFile()
{
// 构建带有标识符的消息
string msg = "DAT " + dlg.FileName;
// 将消息转换为字节数组并发送
socketSent.Send(Encoding.UTF8.GetBytes(msg));
// 打开文件流以读取文件内容
using (FileStream read = new FileStream(dlg.FileName, FileMode.Open, FileAccess.Read))
{
// 定义1KB大小的缓冲区
byte[] buffer = new byte[1024];
int bytesRead;
// 循环读取文件内容并发送
while ((bytesRead = read.Read(buffer, 0, buffer.Length)) > 0)
{
socketSent.Send(buffer, 0, bytesRead, SocketFlags.None);
}
}
// 发送结束标识符
msg = "END";
socketSent.Send(Encoding.UTF8.GetBytes(msg));
// 关闭Socket连接
socketSent.Shutdown(SocketShutdown.Both);
socketSent.Close();
}
}
}