先说服务端:界面:如图:

界面设计源码

namespace SocketJPGToTxt
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null; /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
} #region Windows 窗体设计器生成的代码 /// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.txtMsg = new System.Windows.Forms.TextBox();
this.txtPort = new System.Windows.Forms.TextBox();
this.btnStart = new System.Windows.Forms.Button();
this.cboUsers = new System.Windows.Forms.ComboBox();
this.listBox2 = new System.Windows.Forms.ListBox();
this.txtPath = new System.Windows.Forms.TextBox();
this.btnSelect = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.btnSend = new System.Windows.Forms.Button();
this.btnZD = new System.Windows.Forms.Button();
this.txtLog = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// txtMsg
//
this.txtMsg.Location = new System.Drawing.Point(, );
this.txtMsg.Name = "txtMsg";
this.txtMsg.Size = new System.Drawing.Size(, );
this.txtMsg.TabIndex = ;
this.txtMsg.Text = "127.0.0.1";
//
// txtPort
//
this.txtPort.Location = new System.Drawing.Point(, );
this.txtPort.Name = "txtPort";
this.txtPort.Size = new System.Drawing.Size(, );
this.txtPort.TabIndex = ;
this.txtPort.Text = "";
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(, );
this.btnStart.Name = "btnStart";
this.btnStart.Size = new System.Drawing.Size(, );
this.btnStart.TabIndex = ;
this.btnStart.Text = "开启监听";
this.btnStart.UseVisualStyleBackColor = true;
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
//
// cboUsers
//
this.cboUsers.FormattingEnabled = true;
this.cboUsers.Location = new System.Drawing.Point(, );
this.cboUsers.Name = "cboUsers";
this.cboUsers.Size = new System.Drawing.Size(, );
this.cboUsers.TabIndex = ;
//
// listBox2
//
this.listBox2.FormattingEnabled = true;
this.listBox2.ItemHeight = ;
this.listBox2.Location = new System.Drawing.Point(, );
this.listBox2.Name = "listBox2";
this.listBox2.Size = new System.Drawing.Size(, );
this.listBox2.TabIndex = ;
//
// txtPath
//
this.txtPath.Location = new System.Drawing.Point(, );
this.txtPath.Name = "txtPath";
this.txtPath.Size = new System.Drawing.Size(, );
this.txtPath.TabIndex = ;
//
// btnSelect
//
this.btnSelect.Location = new System.Drawing.Point(, );
this.btnSelect.Name = "btnSelect";
this.btnSelect.Size = new System.Drawing.Size(, );
this.btnSelect.TabIndex = ;
this.btnSelect.Text = "浏览";
this.btnSelect.UseVisualStyleBackColor = true;
this.btnSelect.Click += new System.EventHandler(this.btnSelect_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(, );
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(, );
this.button3.TabIndex = ;
this.button3.Text = "发送文件";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.btnSendFile_Click);
//
// btnSend
//
this.btnSend.Location = new System.Drawing.Point(, );
this.btnSend.Name = "btnSend";
this.btnSend.Size = new System.Drawing.Size(, );
this.btnSend.TabIndex = ;
this.btnSend.Text = "发送消息";
this.btnSend.UseVisualStyleBackColor = true;
this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
//
// btnZD
//
this.btnZD.Location = new System.Drawing.Point(, );
this.btnZD.Name = "btnZD";
this.btnZD.Size = new System.Drawing.Size(, );
this.btnZD.TabIndex = ;
this.btnZD.Text = "震动";
this.btnZD.UseVisualStyleBackColor = true;
this.btnZD.Click += new System.EventHandler(this.btnZD_Click);
//
// txtLog
//
this.txtLog.Location = new System.Drawing.Point(, );
this.txtLog.Multiline = true;
this.txtLog.Name = "txtLog";
this.txtLog.Size = new System.Drawing.Size(, );
this.txtLog.TabIndex = ;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(, );
this.Controls.Add(this.txtLog);
this.Controls.Add(this.btnZD);
this.Controls.Add(this.btnSend);
this.Controls.Add(this.button3);
this.Controls.Add(this.btnSelect);
this.Controls.Add(this.txtPath);
this.Controls.Add(this.listBox2);
this.Controls.Add(this.cboUsers);
this.Controls.Add(this.btnStart);
this.Controls.Add(this.txtPort);
this.Controls.Add(this.txtMsg);
this.Name = "Form1";
this.Text = "Socket服务端";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtMsg;
private System.Windows.Forms.TextBox txtPort;
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.ComboBox cboUsers;
private System.Windows.Forms.ListBox listBox2;
private System.Windows.Forms.TextBox txtPath;
private System.Windows.Forms.Button btnSelect;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button btnSend;
private System.Windows.Forms.Button btnZD;
private System.Windows.Forms.TextBox txtLog;
}
}

界面逻辑源码

namespace SocketJPGToTxt
{
public partial class Form1 : Form
{
//说明:在传递信息的时候,会在需要传递的信息前面加一个字符来标识传递的是不同的信息
// 0:表示传递的是字符串信息
// 1:表示传递的是文件信息
// 2:表示的是震动 /// <summary>
/// 用来存放连接服务的客户端的IP地址和端口号,对应的Socket
/// </summary>
Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>(); public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
//不检测跨线程之间的空间调用
Control.CheckForIllegalCrossThreadCalls = false;
} /// <summary>
/// 开启监听
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStart_Click(object sender, EventArgs e)
{
try
{
//当点击开始监听的时候 在服务器端创建一个负责监IP地址跟端口号的Socket
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//获取IP
IPAddress ip = IPAddress.Any;
//创建端口号
IPEndPoint port = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
//监听
socketWatch.Bind(port);
ShowMsg("监听成功");
socketWatch.Listen();
//新建线程,去接收客户端发来的信息
Thread td = new Thread(AcceptMgs);
td.IsBackground = true;
td.Start(socketWatch);
}
catch
{ }
} /// <summary>
/// 接收客户端发送的信息
/// </summary>
/// <param name="o"></param>
private void AcceptMgs(object o)
{
try
{
Socket socketWatc = (Socket)o;
while (true)
{
////负责跟客户端通信的Socket
Socket socketSend = socketWatc.Accept();
//将远程连接的客户端的IP地址和Socket存入集合中
dicSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
//将远程连接的客户端的IP地址和端口号存储下拉框中
cboUsers.Items.Add(socketSend.RemoteEndPoint.ToString());
ShowMsg(socketSend.RemoteEndPoint.ToString() + ": 连接成功");
//新建线程循环接收客户端发来的信息
Thread td = new Thread(Recive);
td.IsBackground = true;
td.Start(socketSend);
}
}
catch { } } /// <summary>
/// 接收客户端发来的数据,并显示出来
/// </summary>
private void Recive(object o)
{
Socket socketSend = (Socket)o;
try
{
while (true)
{
//客户端连接成功后,服务器应该接受客户端发来的消息 if (socketSend == null)
{
MessageBox.Show("请选择要发送的客户端");
continue;
}
byte[] buffer = new byte[ * * ];
//实际接受到的有效字节数
int r = socketSend.Receive(buffer);
//如果客户端关闭,发送的数据就为空,然后就跳出循环
if (r == )
{
break;
}
if (buffer[] == ) //如果接收的字节数组的第一个字节是0,说明接收的字符串信息
{
string strMsg = Encoding.UTF8.GetString(buffer, , r - );
ShowMsg(socketSend.RemoteEndPoint.ToString() + ": " + strMsg);
}
else if (buffer[] == ) //如果接收的字节数组的第一个字节是1,说明接收的是文件
{
string filePath = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "保存文件";
sfd.InitialDirectory = @"C:\Users\Administrator\Desktop";
sfd.Filter = "文本文件|*.txt|图片文件|*.jpg|视频文件|*.avi|所有文件|*.*";
//如果没有选择保存文件路径就一直打开保存框
while (true)
{
sfd.ShowDialog(this);
filePath = sfd.FileName;
if (string.IsNullOrEmpty(filePath))
{
continue;
}
else
{
break;
}
}
//保存接收的文件
using (FileStream fsWrite = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
{
fsWrite.Write(buffer, , r - );
}
ShowMsg(socketSend.RemoteEndPoint + ": 接收文件成功"); }
else if (buffer[] == ) //如果接收的字节数组的第一个字节是2,说明接收的是震动
{
ZD();
}
}
}
catch { }
} /// <summary>
/// 显示信息
/// </summary>
/// <param name="message"></param>
private void ShowMsg(string message)
{
txtLog.AppendText(message + "\r\n");
} /// <summary>
/// 发送信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{ //获得选中客户端ip对应的通信Socket
if (cboUsers.SelectedItem == null)
{
MessageBox.Show("请选择要发送的客户端");
return;
}
Socket socketSend = dicSocket[cboUsers.SelectedItem.ToString()];
if (socketSend == null)
{
MessageBox.Show("请选择要发送的客户端");
return;
}
string strSend = txtMsg.Text;
try
{
byte[] buffer = Encoding.UTF8.GetBytes(strSend);
//获得发送的信息时候,在数组前面加上一个字节 0
List<byte> list = new List<byte>();
list.Add();
list.AddRange(buffer);
//将泛型集合转换为数组
byte[] newBuffer = list.ToArray();
//将了标识字符的字节数组传递给客户端
socketSend.Send(newBuffer);
txtMsg.Text = "";
}
catch
{
}
} /// <summary>
/// 选择文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSelect_Click(object sender, EventArgs e)
{
//打开文件
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "选择要传的文件";
ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";
ofd.Filter = "文本文件|*.txt|图片文件|*.jpg|视频文件|*.avi|所有文件|*.*";
ofd.ShowDialog();
//得到选择文件的路径
txtPath.Text = ofd.FileName;
} /// <summary>
/// 发送文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSendFile_Click(object sender, EventArgs e)
{
//判断是否选择了要发送的客户端
if (cboUsers.SelectedItem == null)
{
MessageBox.Show("请选择要发送的客户端");
return;
}
Socket socketSend = dicSocket[cboUsers.SelectedItem.ToString()];
if (socketSend == null)
{
MessageBox.Show("请选择要发送的客户端");
return;
}
string filePath = txtPath.Text;
if (string.IsNullOrEmpty(filePath))
{
MessageBox.Show("请选择文件");
return;
}
Thread td = new Thread(SendBigFile);
td.IsBackground = true;
td.Start(); } /// <summary>
/// 大文件断点传送
/// </summary>
private void SendBigFile()
{
string filePath = txtPath.Text;
Socket socketSend = dicSocket[cboUsers.SelectedItem.ToString()];
try
{
//读取选择的文件
using (FileStream fsRead = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read))
{
//1. 第一步:发送一个包,表示文件的长度,让客户端知道后续要接收几个包来重新组织成一个文件
long length = fsRead.Length;
byte[] byteLength = Encoding.UTF8.GetBytes(length.ToString());
//获得发送的信息时候,在数组前面加上一个字节 1
List<byte> list = new List<byte>();
list.Add();
list.AddRange(byteLength);
socketSend.Send(list.ToArray()); //
//2. 第二步:每次发送一个1MB的包,如果文件较大,则会拆分为多个包
byte[] buffer = new byte[ * ];
long send = ; //发送的字节数
while (true) //大文件断点多次传输
{
int r = fsRead.Read(buffer, , buffer.Length);
if (r == )
{
break;
}
socketSend.Send(buffer, , r, SocketFlags.None);
send += r;
ShowMsg(string.Format("{0}: 已发送:{1}/{2}", socketSend.RemoteEndPoint, send, length));
}
ShowMsg("发送完成");
txtPath.Text = "";
}
}
catch
{ }
} /// <summary>
/// 震动
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnZD_Click(object sender, EventArgs e)
{
//判断是否选择了要发送的客户端
if (cboUsers.SelectedItem == null)
{
MessageBox.Show("请选择要发送的客户端");
return;
}
Socket socketSend = dicSocket[cboUsers.SelectedItem.ToString()];
if (socketSend == null)
{
MessageBox.Show("请选择要发送的客户端");
return;
}
try
{
// 首字节是2说明是震动
byte[] buffer = new byte[];
buffer[] = ;
socketSend.Send(buffer);
}
catch
{ } } /// <summary>
/// 震动
/// </summary>
private void ZD()
{
//获取当前窗体的坐标
Point point = this.Location;
//反复给窗体坐标复制一百次,达到震动的效果
for (int i = ; i < ; i++)
{
this.Location = new Point(point.X - , point.Y - );
this.Location = new Point(point.X + , point.Y + );
}
this.Location = point;
}
}
}

然后客户端界面:

客户端界面源码:

namespace SocketJPGToTxtClient
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null; /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
} #region Windows 窗体设计器生成的代码 /// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.txtLog = new System.Windows.Forms.TextBox();
this.btnZD = new System.Windows.Forms.Button();
this.btnSend = new System.Windows.Forms.Button();
this.btnSendFile = new System.Windows.Forms.Button();
this.btnSelect = new System.Windows.Forms.Button();
this.txtPath = new System.Windows.Forms.TextBox();
this.listBox2 = new System.Windows.Forms.ListBox();
this.cboUsers = new System.Windows.Forms.ComboBox();
this.btnStart = new System.Windows.Forms.Button();
this.txtPort = new System.Windows.Forms.TextBox();
this.txtServer = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// txtLog
//
this.txtLog.Location = new System.Drawing.Point(, );
this.txtLog.Multiline = true;
this.txtLog.Name = "txtLog";
this.txtLog.Size = new System.Drawing.Size(, );
this.txtLog.TabIndex = ;
//
// btnZD
//
this.btnZD.Location = new System.Drawing.Point(, );
this.btnZD.Name = "btnZD";
this.btnZD.Size = new System.Drawing.Size(, );
this.btnZD.TabIndex = ;
this.btnZD.Text = "震动";
this.btnZD.UseVisualStyleBackColor = true;
this.btnZD.Click += new System.EventHandler(this.btnZD_Click);
//
// btnSend
//
this.btnSend.Location = new System.Drawing.Point(, );
this.btnSend.Name = "btnSend";
this.btnSend.Size = new System.Drawing.Size(, );
this.btnSend.TabIndex = ;
this.btnSend.Text = "发送消息";
this.btnSend.UseVisualStyleBackColor = true;
this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
//
// btnSendFile
//
this.btnSendFile.Location = new System.Drawing.Point(, );
this.btnSendFile.Name = "btnSendFile";
this.btnSendFile.Size = new System.Drawing.Size(, );
this.btnSendFile.TabIndex = ;
this.btnSendFile.Text = "发送文件";
this.btnSendFile.UseVisualStyleBackColor = true;
this.btnSendFile.Click += new System.EventHandler(this.btnSendFile_Click);
//
// btnSelect
//
this.btnSelect.Location = new System.Drawing.Point(, );
this.btnSelect.Name = "btnSelect";
this.btnSelect.Size = new System.Drawing.Size(, );
this.btnSelect.TabIndex = ;
this.btnSelect.Text = "浏览";
this.btnSelect.UseVisualStyleBackColor = true;
this.btnSelect.Click += new System.EventHandler(this.btnSelect_Click);
//
// txtPath
//
this.txtPath.Location = new System.Drawing.Point(, );
this.txtPath.Name = "txtPath";
this.txtPath.Size = new System.Drawing.Size(, );
this.txtPath.TabIndex = ;
//
// listBox2
//
this.listBox2.FormattingEnabled = true;
this.listBox2.ItemHeight = ;
this.listBox2.Location = new System.Drawing.Point(, );
this.listBox2.Name = "listBox2";
this.listBox2.Size = new System.Drawing.Size(, );
this.listBox2.TabIndex = ;
//
// cboUsers
//
this.cboUsers.FormattingEnabled = true;
this.cboUsers.Location = new System.Drawing.Point(, );
this.cboUsers.Name = "cboUsers";
this.cboUsers.Size = new System.Drawing.Size(, );
this.cboUsers.TabIndex = ;
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(, );
this.btnStart.Name = "btnStart";
this.btnStart.Size = new System.Drawing.Size(, );
this.btnStart.TabIndex = ;
this.btnStart.Text = "连接";
this.btnStart.UseVisualStyleBackColor = true;
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
//
// txtPort
//
this.txtPort.Location = new System.Drawing.Point(, );
this.txtPort.Name = "txtPort";
this.txtPort.Size = new System.Drawing.Size(, );
this.txtPort.TabIndex = ;
this.txtPort.Text = "";
//
// txtServer
//
this.txtServer.Location = new System.Drawing.Point(, );
this.txtServer.Name = "txtServer";
this.txtServer.Size = new System.Drawing.Size(, );
this.txtServer.TabIndex = ;
this.txtServer.Text = "127.0.0.1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(, );
this.Controls.Add(this.txtLog);
this.Controls.Add(this.btnZD);
this.Controls.Add(this.btnSend);
this.Controls.Add(this.btnSendFile);
this.Controls.Add(this.btnSelect);
this.Controls.Add(this.txtPath);
this.Controls.Add(this.listBox2);
this.Controls.Add(this.cboUsers);
this.Controls.Add(this.btnStart);
this.Controls.Add(this.txtPort);
this.Controls.Add(this.txtServer);
this.Name = "Form1";
this.Text = "Client";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtLog;
private System.Windows.Forms.Button btnZD;
private System.Windows.Forms.Button btnSend;
private System.Windows.Forms.Button btnSendFile;
private System.Windows.Forms.Button btnSelect;
private System.Windows.Forms.TextBox txtPath;
private System.Windows.Forms.ListBox listBox2;
private System.Windows.Forms.ComboBox cboUsers;
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.TextBox txtPort;
private System.Windows.Forms.TextBox txtServer;
}
}

客户端界面逻辑代码

namespace SocketJPGToTxtClient
{
public partial class Form1 : Form
{
//说明:在传递信息的时候,会在需要传递的信息前面加一个字符来标识传递的是不同的信息
// 0:表示传递的是字符串信息
// 1:表示传递的是文件信息
// 2:表示的是震动 /// <summary>
/// 用来存放连接服务的IP地址和端口号,对应的Socket (这个为了以后的扩展用,现在暂时没用)
/// </summary>
Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>(); /// <summary>
/// 存储保存文件的路径
/// </summary>
string filePath = "";
/// <summary>
/// 负责通信的Socket
/// </summary>
Socket socketSend; public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
//不检测跨线程之间的空间调用
Control.CheckForIllegalCrossThreadCalls = false;
} /// <summary>
/// 建立连接
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStart_Click(object sender, EventArgs e)
{
try
{
//创建负责通信的Socket
socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//获取服务端的IP
IPAddress ip = IPAddress.Parse(txtServer.Text.Trim());
//获取服务端的端口号
IPEndPoint port = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
//获得要连接的远程服务器应用程序的IP地址和端口号
socketSend.Connect(port);
ShowMsg("连接成功");
//新建线程,去接收客户端发来的信息
Thread td = new Thread(AcceptMgs);
td.IsBackground = true;
td.Start();
}
catch { }
} /// <summary>
/// 接收数据
/// </summary>
private void AcceptMgs()
{
try
{
/// <summary>
/// 存储大文件的大小
/// </summary>
long length = ;
long recive = ; //接收的大文件总的字节数
while (true)
{
byte[] buffer = new byte[ * ];
int r = socketSend.Receive(buffer);
if (r == )
{
break;
}
if (length > ) //判断大文件是否已经保存完
{
//保存接收的文件
using (FileStream fsWrite = new FileStream(filePath, FileMode.Append, FileAccess.Write))
{
fsWrite.Write(buffer, , r);
length -= r; //减去每次保存的字节数
ShowMsg(string.Format("{0}: 已接收:{1}/{2}", socketSend.RemoteEndPoint, recive - length, recive));
if (length <= )
{
ShowMsg(socketSend.RemoteEndPoint + ": 接收文件成功");
}
continue;
}
}
if (buffer[] == ) //如果接收的字节数组的第一个字节是0,说明接收的字符串信息
{
string strMsg = Encoding.UTF8.GetString(buffer, , r - );
ShowMsg(socketSend.RemoteEndPoint.ToString() + ": " + strMsg);
}
else if (buffer[] == ) //如果接收的字节数组的第一个字节是1,说明接收的是文件
{
length = int.Parse(Encoding.UTF8.GetString(buffer, , r - ));
recive = length;
filePath = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "保存文件";
sfd.InitialDirectory = @"C:\Users\Administrator\Desktop";
sfd.Filter = "文本文件|*.txt|图片文件|*.jpg|视频文件|*.avi|所有文件|*.*";
//如果没有选择保存文件路径就一直打开保存框
while (true)
{
sfd.ShowDialog(this);
filePath = sfd.FileName;
if (string.IsNullOrEmpty(filePath))
{
continue;
}
else
{
break;
}
}
}
else if (buffer[] == ) //如果接收的字节数组的第一个字节是2,说明接收的是震动
{
ZD();
}
}
}
catch { } } /// <summary>
/// 显示信息
/// </summary>
/// <param name="message"></param>
private void ShowMsg(string message)
{
txtLog.AppendText(message + "\r\n");
} /// <summary>
/// 发送数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
try
{
byte[] buffer = Encoding.UTF8.GetBytes(txtServer.Text);
//获得发送的信息时候,在数组前面加上一个字节 0
List<byte> list = new List<byte>();
list.Add();
list.AddRange(buffer);
//将泛型集合转换为数组
byte[] newBuffer = list.ToArray();
//将了标识字符的字节数组传递给客户端
socketSend.Send(newBuffer);
txtServer.Text = "";
}
catch { }
} /// <summary>
/// 选择文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSelect_Click(object sender, EventArgs e)
{
//打开文件
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "选择要传的文件";
ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";
ofd.Filter = "文本文件|*.txt|图片文件|*.jpg|视频文件|*.avi|所有文件|*.*";
ofd.ShowDialog();
//得到选择文件的路径
txtPath.Text = ofd.FileName;
} /// <summary>
/// 发送文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSendFile_Click(object sender, EventArgs e)
{
try
{
string filePath = txtPath.Text;
if (string.IsNullOrEmpty(filePath))
{
MessageBox.Show("请选择文件");
return;
}
//读取选择的文件
using (FileStream fsRead = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read))
{
byte[] buffer = new byte[ * * ];
int r = fsRead.Read(buffer, , buffer.Length);
//获得发送的信息时候,在数组前面加上一个字节 1
List<byte> list = new List<byte>();
list.Add();
list.AddRange(buffer);
byte[] newBuffer = list.ToArray();
//将了标识字符的字节数组传递给客户端
socketSend.Send(newBuffer, , r + , SocketFlags.None);
txtPath.Text = "";
}
}
catch { }
} /// <summary>
/// 震动
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnZD_Click(object sender, EventArgs e)
{
try
{
// 首字节是2说明是震动
byte[] buffer = new byte[];
buffer[] = ;
socketSend.Send(buffer);
}
catch { }
} /// <summary>
/// 震动
/// </summary>
private void ZD()
{
//获取当前窗体的坐标
Point point = this.Location;
//反复给窗体坐标复制一百次,达到震动的效果
for (int i = ; i < ; i++)
{
this.Location = new Point(point.X - , point.Y - );
this.Location = new Point(point.X + , point.Y + );
}
this.Location = point;
} }
}

然后完毕,我觉得挺好的,跟大家分享一下

C# socket 发送图片和文件的更多相关文章

  1. ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(三) 之 实现单聊,群聊,发送图片,文件。

    上篇讲解了如何搭建聊天服务器,以及客户端js怎么和layui的语法配合.服务器已经连接上了,那么聊天还会远吗? 进入正题,正如上一篇提到的我们用 Client.Group(groupId)的方法向客户 ...

  2. 使用ajax发送图片等文件

    1.使用H5的FormData()对象,append()添加文件 2.processData: false, // 告诉jQuery不要去处理发送的数据    contentType: false, ...

  3. socket 发送图片

    using System;using System.Collections.Generic;using System.Text;using System.Net.Sockets;using Syste ...

  4. socket发送文字、图片、文件---基于python实现

    socket官方文档:https://docs.python.org/2/library/socket.html socket中文详细介绍:http://blog.csdn.net/rebelqsp/ ...

  5. C#开发微信门户及应用(19)-微信企业号的消息发送(文本、图片、文件、语音、视频、图文消息等)

    我们知道,企业号主要是面向企业需求而生的,因此内部消息的交流显得非常重要,而且发送.回复消息数量应该很可观,对于大企业尤其如此,因此可以结合企业号实现内部消息的交流.企业号具有关注安全.消息无限制等特 ...

  6. C#使用FileSystemWatcher来监控指定文件夹,并使用TCP/IP协议通过Socket发送到另外指定文件夹

    项目需求: 局域网内有两台电脑,电脑A(Windows系统)主要是负责接收一些文件(远程桌面粘贴.FTP上传.文件夹共享等方式),希望能在A接收文件后自动传输到电脑B(Windows系统)来做一个备份 ...

  7. 客户端模拟线程线程池发送100个文件给socket

    1.线程池模拟发送100个线程发送 2.每个线程启动一个socket发送文件 3.线程池最大并发几个

  8. Socket通讯-C#客户端与Java服务端通讯(发送消息和文件)

    设计思路 使用websocket通信,客户端采用C#开发界面,服务端使用Java开发,最终实现Java服务端向C#客户端发送消息和文件,C#客户端实现语音广播的功能. Java服务端设计 packag ...

  9. android开发 socket接收图片并保存

    逻辑:接收到socket之后需要将socket发送的图片数据保存下来并通知handler更新界面 关键代码: public void readImage(Socket socket) { try { ...

随机推荐

  1. linux weblogic 控制台进入缓慢

    实际是JVM在Linux下的bug 他想调用一个随机函数 但取不到 暂时的解决办法是 1)较好的解决办法: 在Weblogic启动参数里添加 “- Djava.security.egd=file:/d ...

  2. 阿里云服务器搭建SVN

    简单步骤介绍 1:安装svn apt-get install subversion 2. 开启svn服务器 svnserve -d 检查是否开启:ps aux | grep svnserve 若出现如 ...

  3. 开源方案搭建可离线的精美矢量切片地图服务-6.Mapbox之.pbf字体库

    项目成果展示(所有项目文件都在阿里云的共享云虚拟主机上,访问地图可以会有点慢,请多多包涵). 01:中国地图:http://test.sharegis.cn/mapbox/html/3china.ht ...

  4. C输入输出与文件

    一.终端I/O 1.单字符I/O:getchar(),putchar() (1)单字符输入(get character): [ int getchar();] 返回值为输入的字符(ASCII).可以接 ...

  5. 浅析Java源码之HashMap外传-红黑树Treenode(已鸽)

    (这篇文章暂时鸽了,有点理解不能,点进来的小伙伴可以撤了) 刚开始准备在HashMap中直接把红黑树也过了的,结果发现这个类不是一般的麻烦,所以单独开一篇. 由于红黑树之前完全没接触过,所以这篇博客相 ...

  6. 微信公众号支付回调页面处理asp.net

    1.在商家微信商户通中配置回调url 2.在提交订单时传入的回调页面中获取支付成功后或支付失败后的参数,对订单进行处理 public partial class gzpayCallback : Sys ...

  7. Git(二)_基本命令

    0. 开始查看所有配置:git config --listgit config --global user.name "runoob"git config --global use ...

  8. windows下nodejs监听80端口

    windows下nodejs监听80端口时提示端口被占用报错,解决方案如下: 1.cmd---netstat -ano查看是什么程序占用了80端口: 2.控制面板--管理工具--服务--停止 SQL ...

  9. 表达式树(Expression Trees)

    [翻译]表达式树(Expression Trees) 原文地址:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/con ...

  10. [日常] Go语言圣经-指针对象的方法-bit数组习题

    练习6.1: 为bit数组实现下面这些方法 func (*IntSet) Len() int // return the number of elements func (*IntSet) Remov ...