FileSendClient :

Form1.cs

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms; namespace FileSendClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
FileDialog fDg = new OpenFileDialog();
if (fDg.ShowDialog() == DialogResult.OK)
{
FTClientCode.SendFile(fDg.FileName);
}
} private void timer1_Tick(object sender, EventArgs e)
{
label3.Text = FTClientCode.curMsg;
}
} //FILE TRANSFER USING C#.NET SOCKET - CLIENT
class FTClientCode
{
public static string curMsg = "Idle";
public static void SendFile(string fileName)
{
try
{
// IPAddress ipAddress = Dns.GetHostEntry("109.52.62.59").AddressList[0]; IPAddress ipAddress2 = Dns.GetHostAddresses("109.52.62.59")[]; IPEndPoint ipEnd = new IPEndPoint(ipAddress2, );
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); string filePath = ""; fileName = fileName.Replace("\\", "/");
while (fileName.IndexOf("/") > -)
{
filePath += fileName.Substring(, fileName.IndexOf("/") + );
fileName = fileName.Substring(fileName.IndexOf("/") + );
} byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
if (fileNameByte.Length > * )
{
curMsg = "File size is more than 850kb, please try with small file.";
return;
} curMsg = "Buffering ...";
byte[] fileData = File.ReadAllBytes(filePath + fileName);
byte[] clientData = new byte[ + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length); fileNameLen.CopyTo(clientData, );
fileNameByte.CopyTo(clientData, );
fileData.CopyTo(clientData, + fileNameByte.Length); curMsg = "Connection to server ...";
clientSock.Connect(ipEnd); curMsg = "File sending...";
clientSock.Send(clientData); curMsg = "Disconnecting...";
clientSock.Close();
curMsg = "File transferred."; }
catch (Exception ex)
{
if (ex.Message == "No connection could be made because the target machine actively refused it")
curMsg = "File Sending fail. Because server not running.";
else
curMsg = "File Sending fail." + ex.Message;
} } public static IPAddress GetLocalIP()
{
IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
foreach (IPAddress ipAddress in addressList)
{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
return ipAddress;
}
return addressList[];
}
}
}

Form1.Designer.cs

namespace FileSendClient
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null; /// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
} #region Windows Form Designer generated code /// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(, );
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(, );
this.button1.TabIndex = ;
this.button1.Text = "Select File to Send";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)()));
this.label1.ForeColor = System.Drawing.Color.Green;
this.label1.Location = new System.Drawing.Point(, );
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(, );
this.label1.TabIndex = ;
this.label1.Text = "That program can transfer small file. I\'ve test up to 1.5MB file";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(, );
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(, );
this.label2.TabIndex = ;
this.label2.Text = "Present Status:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(, );
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(, );
this.label3.TabIndex = ;
this.label3.Text = "Idle";
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = ;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(, );
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Timer timer1;
}
}

FileSendServer

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms; namespace FileSendServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FTServerCode.receivedPath = "";
} private void button1_Click(object sender, EventArgs e)
{
if (FTServerCode.receivedPath.Length > )
backgroundWorker1.RunWorkerAsync();
else
MessageBox.Show("Please select file receiving path");
} private void timer1_Tick(object sender, EventArgs e)
{
label5.Text = FTServerCode.receivedPath;
label3.Text = FTServerCode.curMsg;
} FTServerCode obj = new FTServerCode();
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{ obj.StartServer();
} private void button2_Click(object sender, EventArgs e)
{
FolderBrowserDialog fd = new FolderBrowserDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
FTServerCode.receivedPath = fd.SelectedPath;
}
}
}
//FILE TRANSFER USING C#.NET SOCKET - SERVER
class FTServerCode
{
IPEndPoint ipEnd;
Socket sock;
public FTServerCode()
{
ipEnd = new IPEndPoint(IPAddress.Any, );
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
}
public static string receivedPath;
public static string curMsg = "Stopped";
public void StartServer()
{
try
{
curMsg = "Starting...";
sock.Listen(); curMsg = "Running and waiting to receive file.";
Socket clientSock = sock.Accept(); byte[] clientData = new byte[ * ]; int receivedBytesLen = clientSock.Receive(clientData);
curMsg = "Receiving data..."; int fileNameLen = BitConverter.ToInt32(clientData, );
string fileName = Encoding.ASCII.GetString(clientData, , fileNameLen); BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + "/" + fileName, FileMode.Append)); ;
bWrite.Write(clientData, + fileNameLen, receivedBytesLen - - fileNameLen); curMsg = "Saving file..."; bWrite.Close();
clientSock.Close();
curMsg = "Reeived & Saved file; Server Stopped.";
}
catch (Exception ex)
{
curMsg = "File Receving error.";
}
}
}
}

Form1.Designer.cs

namespace FileSendServer
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null; /// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
} #region Windows Form Designer generated code /// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.button1 = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
this.button2 = new System.Windows.Forms.Button();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(, );
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(, );
this.button1.TabIndex = ;
this.button1.Text = "Start Server";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(, );
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(, );
this.label2.TabIndex = ;
this.label2.Text = "Server Status:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(, );
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(, );
this.label3.TabIndex = ;
this.label3.Text = "Stopped";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)()));
this.label4.ForeColor = System.Drawing.Color.ForestGreen;
this.label4.Location = new System.Drawing.Point(, );
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(, );
this.label4.TabIndex = ;
this.label4.Text = "That program can transfer small file. I\'ve test up to 1.5MB file";
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = ;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// backgroundWorker1
//
this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
//
// button2
//
this.button2.Location = new System.Drawing.Point(, );
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(, );
this.button2.TabIndex = ;
this.button2.Text = "Select Receiving Path";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(, );
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(, );
this.label5.TabIndex = ;
this.label5.Text = " ";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(, );
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(, );
this.label6.TabIndex = ;
this.label6.Text = "File receiving path:";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(, );
this.Controls.Add(this.label5);
this.Controls.Add(this.label6);
this.Controls.Add(this.button2);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Timer timer1;
private System.ComponentModel.BackgroundWorker backgroundWorker1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
}
}

[通信] C#多线程Socket-文件传输的更多相关文章

  1. 基于序列化技术(Protobuf)的socket文件传输

    好像好久都没更博文了,没办法,最近各种倒霉事情,搞到最近真的没什么心情,希望之后能够转运吧. 言归正传,这次我要做的是基于序列化技术的socket文件传输来无聊练一下手. 一.socket文件传输 之 ...

  2. Socket 文件传输

    服务端 1.控件:TServerSocket 2.OnClientRead事件处理 procedure TMainForm.ssClientRead(Sender: TObject; Socket: ...

  3. Linux网络编程:socket文件传输范例

    基于TCP流协议的socket网络文件传输Demo: 实现:C语言功能:文件传输(可以传任何格式的文件) /********************************************** ...

  4. python socket文件传输实现

    简单版 server(服务端) import socket import subprocess import struct import json import os share_dir = r'E: ...

  5. Android连接热点的Socket文件传输

    最近把测试丢过来的种种BUG解决后,终于有时间去研究研究Socket通信,再加上以前做的WiFi连接和热点开启,于是有了现在的这篇博文:创建热点发送文件,让另一台手机连接热点接收文件. 效果图: 两台 ...

  6. python 3.7 利用socket文件传输

    参考:https://www.cnblogs.com/VseYoung/p/socket_1.html 参考 https://blog.csdn.net/a19990412/article/detai ...

  7. Java基于Socket文件传输示例(转)

    最近需要进行网络传输大文件,于是对基于socket的文件传输作了一个初步的了解.在一位网友提供的程序基础上,俺进行了一些加工,采用了缓冲输入/输出流来包装输出流,再采用数据输入/输出输出流进行包装,加 ...

  8. Java基于Socket文件传输示例

    http://www.blogjava.net/sterning/archive/2007/10/13/152508.html 最近需要进行网络传输大文件,于是对基于socket的文件传输作了一个初步 ...

  9. Qt实现基于多线程的文件传输(服务端,客户端)

    1. 效果 先看看效果图 这是传输文件完成的界面 客户端 服务端 2. 知识准备 其实文件传输和聊天室十分相似,只不过一个传输的是文字,一个传输的是文件,而这方面的知识,我已经在前面的博客写过了,不了 ...

  10. [Socket]Socket文件传输

    1.Server import java.io.DataInputStream; import java.io.FileOutputStream; import java.io.IOException ...

随机推荐

  1. Oracle:oracle 12.1.0.2 升级到12.2.0.1 后,自动任务报错:ORA-20001: Statistics Advisor: Invalid task name for the current user

    具体错误如下:关键字:ORA-12012.ORA-20001 ORA-12012: error on auto execute of job "SYS"."ORA$AT_ ...

  2. MysqlHelper使用反射机制智能推算数据类型以及属性名称

    public class MySqlHelper { private string ConnString; public MySqlHelper(string connectionString) { ...

  3. mysql中json_remove函数的使用?

    需求描述: 今天看json记录,可以通过json_remove函数对一个key或多个key从个json记录中去掉. 操作过程: 1.查看一个已经存在的json表 mysql> select * ...

  4. Vim 操作符命令和动作命令

    http://www.cnblogs.com/littlerabbit/articles/2349951.html

  5. SQL Compare数据库比较工具 完全破解+使用教程

    来源http://www.cnblogs.com/duci/articles/4482665.html 一.使用教程 SQL Compare是编程人员常用的比较两个数据库之间差异的工具.可以用来比较数 ...

  6. 解决 iOS7 通过tag 找不到 UITableViewCell 的子控件(转)

    转自:http://www.cnblogs.com/waiwaibuzhidao/p/3340400.html 当iOS7问世,程序的世界就混乱了,以前良好的程序,现在是一塌糊涂,于是只能把问题一个一 ...

  7. C++ 关键字——friend【转载】

    转载自: http://www.cnblogs.com/CBDoctor/archive/2012/02/04/2337733.html 友元是指: 采用类的机制后实现了数据的隐藏与封装,类的数据成员 ...

  8. backbone学习笔记:模型(Model)(2)属性验证

    Backbone的属性验证有2种方法: 1.Backbone自带简单的验证方法,但是验证规则需要自己实现 通过validate()方法进行验证,验证规则写在此方法里. var RoomModel = ...

  9. php前端传过来的json数据丢失 (max_input_vars)

    开发向我反馈,前端业务页面提交数据用js将要传输的数据用json dump后,发给服务器,服务器在loads后发现数据是不全的. 这个问题困扰开发人员和运维人员.首先调整php.ini文件的上传文件数 ...

  10. 使用 redis “捕捉” “用户登录过期” 事件

    实现原理及步骤: 1)登录时,计算登录过期时间,以分钟为单位作key(例如:sign_timeout_201705212233),value方面自己发挥,需要什么数据就拼什么数据进去,只是要注意,一定 ...