服务器端:
///
/// 选择文件按钮
///
///
///
private void btn_Choose_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
opf.Title = "请选择文件";
opf.InitialDirectory = @"C:\Users\qweasd\Pictures\Mays\Vt";
//opf.Multiselect = true;
opf.Filter = "所有文件|.;";
opf.ShowDialog();
textBox1.Text = opf.FileName;//返回选择文件的全路径
}
///
/// 发送文件按钮
///
///
///
private void btn_SendFile_Click(object sender, EventArgs e)
{
string path = textBox1.Text;
//文件流读取
using (FileStream fs = new FileStream (path,FileMode.OpenOrCreate,FileAccess.Read))
{
byte[] date = new byte[1024 * 1024 * 5];
int r = fs.Read(date, 0, date.Length);
//配置标记位
List
list.Add(1);//在文件的字节数组前添加标记位用来判断其文件类型
list.AddRange(date);
byte[] newdate = list.ToArray();
dicSocket[comboBox1.SelectedItem.ToString()].Send(newdate, 0, r + 1, SocketFlags.None);//从0 开始多传输1位数据
}
}
private void btn_DJ_Click(object sender, EventArgs e)
{
byte[] date = new byte[1];
date[0] = 2;//震动标记为2
dicSocket[comboBox1.SelectedItem.ToString()].Send(date);
}
客户端:
在接收服务器端数据的方法中进行判断
private void Receive()
{
while (true)
{
try
{
byte[] buffer = new byte[1023 * 1023 * 2];
int r = socketSend.Receive(buffer);
if (r == 0)
break;
//通过第一个标记位来判断文件类型(简单协议)
if (buffer[0] == 0)//标志位为0时,发送的是普通文本
{
string str = Encoding.UTF8.GetString(buffer, 1, r-1);
ShowMsg(socketSend.RemoteEndPoint + ":" + str);
}else if (buffer[0]==1)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = @"C:\Users\qweasd\Pictures\Mays\Vt\Soc";
sfd.Title = "选择要保存到文件";
sfd.Filter = "所有文件|*.*";
sfd.ShowDialog(this);
string path = sfd.FileName;
using (FileStream fs = new FileStream (path,FileMode.OpenOrCreate,FileAccess.Write))
{
fs.Write(buffer, 1, r - 1);
}
}
else if (buffer[0]==2)
{
Shork();
}
}
catch
{ }
}
}
/// <summary>
/// 震动
/// </summary>
private void Shork()
{
for (int i = 0; i < 500; i++)
{
this.Location = new Point(this.Location.X + 50, this.Location.Y + 50);
this.Location = new Point(this.Location.X - 50, this.Location.Y - 50);
}
}