[通信] C#多线程Socket-文件传输
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-文件传输的更多相关文章
- 基于序列化技术(Protobuf)的socket文件传输
好像好久都没更博文了,没办法,最近各种倒霉事情,搞到最近真的没什么心情,希望之后能够转运吧. 言归正传,这次我要做的是基于序列化技术的socket文件传输来无聊练一下手. 一.socket文件传输 之 ...
- Socket 文件传输
服务端 1.控件:TServerSocket 2.OnClientRead事件处理 procedure TMainForm.ssClientRead(Sender: TObject; Socket: ...
- Linux网络编程:socket文件传输范例
基于TCP流协议的socket网络文件传输Demo: 实现:C语言功能:文件传输(可以传任何格式的文件) /********************************************** ...
- python socket文件传输实现
简单版 server(服务端) import socket import subprocess import struct import json import os share_dir = r'E: ...
- Android连接热点的Socket文件传输
最近把测试丢过来的种种BUG解决后,终于有时间去研究研究Socket通信,再加上以前做的WiFi连接和热点开启,于是有了现在的这篇博文:创建热点发送文件,让另一台手机连接热点接收文件. 效果图: 两台 ...
- python 3.7 利用socket文件传输
参考:https://www.cnblogs.com/VseYoung/p/socket_1.html 参考 https://blog.csdn.net/a19990412/article/detai ...
- Java基于Socket文件传输示例(转)
最近需要进行网络传输大文件,于是对基于socket的文件传输作了一个初步的了解.在一位网友提供的程序基础上,俺进行了一些加工,采用了缓冲输入/输出流来包装输出流,再采用数据输入/输出输出流进行包装,加 ...
- Java基于Socket文件传输示例
http://www.blogjava.net/sterning/archive/2007/10/13/152508.html 最近需要进行网络传输大文件,于是对基于socket的文件传输作了一个初步 ...
- Qt实现基于多线程的文件传输(服务端,客户端)
1. 效果 先看看效果图 这是传输文件完成的界面 客户端 服务端 2. 知识准备 其实文件传输和聊天室十分相似,只不过一个传输的是文字,一个传输的是文件,而这方面的知识,我已经在前面的博客写过了,不了 ...
- [Socket]Socket文件传输
1.Server import java.io.DataInputStream; import java.io.FileOutputStream; import java.io.IOException ...
随机推荐
- thinkphp3.2 控制器导入模型
方法一: public function index(){ $Member = new MemberModel(); $money = $Member->Money(); print_r($mo ...
- Java初学者不可不知的MyEclipse的设置技巧(自动联想功能)
最近初学Java,正在使用MyEclipse来编写新的项目,刚开始打开MyEclipse感觉这个工具既陌生又熟悉,熟悉之处在于编辑器的几大共通之处它都具备,比如说基本的设置.编辑区.调试区都是类似的, ...
- python05 - 迭代器,生成器,装饰器
迭代器 迭代器就是访问集合元素的一种方式,迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问一遍后结束. 迭代器很大的特点: 只能往前迭代,不能够回退,也不能随机访问其中一个元素,只能通过__ ...
- mysql 两台主主复制配置
A.服务器 [mysqld] # The TCP/IP Port the MySQL Server will listen on port= server-id= #master-host=10.1. ...
- Do you want a timeout?
Do you want a timeout? You’re feeling accomplished and excited; the new features for your applicat ...
- 关于 wsdl2Java 自动生成客户端调取webservice接口
webservice地址:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl wsdl2Java 自动生成类名: 客户端调 ...
- NHibernate 集合映射深入 (第五篇) <set>,<list>,<map>,<bag>
一.集合外键 在NHibernate中,典型的用于映射集合类的元素有<set>,<list>,<map>,<bag>,<array>,< ...
- MAC下Android的Eclipse开发环境的搭建 转自MacroCheng
原文地址: http://www.cnblogs.com/macro-cheng/archive/2011/09/30/android-001.html 一.Eclipse的下载 到网站:http: ...
- Dubbo -- 系统学习 笔记 -- 示例 -- 静态服务
Dubbo -- 系统学习 笔记 -- 目录 示例 想完整的运行起来,请参见:快速启动,这里只列出各种场景的配置方式 静态服务 有时候希望人工管理服务提供者的上线和下线,此时需将注册中心标识为非动态管 ...
- js数组获取相同元素个数,归档排序
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...