摘要:本文将带你了解C#编程之Winform局域网传送文件,希望本文对大家学C#/.Net有所帮助。
//发送文件
private void btn_sendFile_Click(object sender, EventArgs e)
{
//打开文件
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
//初始化接受套接字:寻址方案,以字符流方式和Tcp通信
socketSent = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
//设置服务器IP地址和端口
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);
//将要发送的文件加上"DAT"标识符
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;
//将 "msg" 转化为字节流的形式进行传送
socketSent.Send(Encoding.Default.GetBytes(msg));
//定义一个读文件流
FileStream read = new FileStream(dlg.FileName, FileMode.Open, FileAccess.Read);
//设置缓冲区为1024byte
byte[] buff = new byte[1024];
int len = 0;
while ((len = read.Read(buff, 0, 1024)) != 0)
{
//按实际的字节总量发送信息
socketSent.Send(buff, 0, len, SocketFlags.None);
}
//将要发送信息的最后加上"END"标识符
msg = "END";
//将 "msg" 发送
socketSent.Send(Encoding.Default.GetBytes(msg));
socketSent.Close();
read.Close();
}
}
}
以上就介绍了C#.NET的相关知识,希望对C#.NET有兴趣的朋友有所帮助。了解更多内容,请关注职坐标编程语言C#.NET频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号