c# socket 服务端与客户端通信演示代码
主要实现服务端与客户端消息和文件的相互发送,服务端可以控制客户端:重启、关机、注销,截屏(截客户端的屏)。服务端也可向客户端发送闪屏。
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.net;
using system.net.sockets;
using system.text;
using system.windows.forms;
using system.io;
using system.threading;
using system.runtime.interopservices;
public delegate void dgshowmsg(string strmsg);
namespace server
{
public partial class form1 : form
{
public form1()
{
initializecomponent();
textbox.checkforillegalcrossthreadcalls = false;//关闭跨线程修改控件检查
// txtip.text = dns.gethostentry(dns.gethostname()).addresslist[0].tostring();
txtip.text = dns.gethostbyname(dns.gethostname()).addresslist[0].tostring();
}
[dllimport(kernel32)] ///获取系统时间
public static extern void getsystemtime(ref systemtime_info stinfo);
///定义系统时间结构信息
[structlayout(layoutkind.sequential)]
public struct systemtime_info
{
public ushort wyear;
public ushort wmonth;
public ushort wdayofweek;
public ushort wday;
public ushort whour;
public ushort wminute;
public ushort wsecond;
public ushort wmilliseconds;
}
socket sokwatch = null;//负责监听 客户端段 连接请求的 套接字(女生宿舍的大妈)
thread threadwatch = null;//负责 调用套接字, 执行 监听请求的线程
//开启监听 按钮
private void btnstartlisten_click(object sender, eventargs e)
{
//实例化 套接字 (ip4寻址协议,流式传输,tcp协议)
sokwatch = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
//创建 ip对象
ipaddress address = ipaddress.parse(txtip.text.trim());
// ipaddress[] addresslist = dns.gethostentry(dns.gethostname()).addresslist;
//string ip= this.geta
//创建网络节点对象 包含 ip和port
// ipendpoint endpoint = new ipendpoint(address, int.parse(txtport.text.trim())); combobox1.text.trim();
ipendpoint endpoint = new ipendpoint(address, int.parse(combobox1.text.trim()));
//将 监听套接字 绑定到 对应的ip和端口
sokwatch.bind(endpoint);
//设置 监听队列 长度为10(同时能够处理 10个连接请求)
sokwatch.listen(20);
threadwatch = new thread(startwatch);
threadwatch.isbackground = true;
threadwatch.start();
//txtshow.appendtext(启动服务器成功......rn);
label4.text = 启动服务器成功......;
}
//dictionary dictsocket = new dictionary();
dictionary dictconn = new dictionary();
bool iswatch = true;
#region 1.被线程调用 监听连接端口
///
/// 被线程调用 监听连接端口
///
void startwatch()
{
string recode;
while (iswatch)
{
//threadwatch.setapartmentstate(apartmentstate.sta);
//监听 客户端 连接请求,但是,accept会阻断当前线程
socket sokmsg = sokwatch.accept();//监听到请求,立即创建负责与该客户端套接字通信的套接字
connectionclient connection = new connectionclient(sokmsg, showmsg, removeclientconnection);
//将负责与当前连接请求客户端 通信的套接字所在的连接通信类 对象 装入集合
dictconn.add(sokmsg.remoteendpoint.tostring(), connection);
//将 通信套接字 加入 集合,并以通信套接字的远程ipport作为键
//dictsocket.add(sokmsg.remoteendpoint.tostring(), sokmsg);
//将 通信套接字的 客户端ip端口保存在下拉框里
cboclient.items.add(sokmsg.remoteendpoint.tostring());
messagebox.show(有一个客户端新添加!);
recode = sokmsg.remoteendpoint.tostring();
//调用getsystemtime函数获取系统时间信息
systemtime_info stinfo; stinfo = new systemtime_info();
getsystemtime(ref stinfo);
recode +=子计算机在+stinfo.wyear.tostring() + 年 + stinfo.wmonth.tostring() + 月 + stinfo.wday.tostring() + 日;
recode += (stinfo.whour + 8).tostring() + 点 + stinfo.wminute.tostring() + 分 + stinfo.wsecond.tostring() + 秒+连接服务;
//记录每台子计算机连接服务主机的日志
streamwriter m_sw = new streamwriter(system.windows.forms.application.startuppath + @\file.dat, true);
m_sw.writeline(recode);
m_sw.writeline(------------------------------------------------------------------);
m_sw.close();
//messagebox.show(recode);
dictconn[sokmsg.remoteendpoint.tostring()].sendtrue();
//启动一个新线程,负责监听该客户端发来的数据
//thread threadconnection = new thread(recivemsg);
//threadconnection.isbackground = true;
//threadconnection.start(sokmsg);
}
}
#endregion
//bool isrec = true;
//与客户端通信的套接字 是否 监听消息
#region 发送消息 到指定的客户端 -btnsend_click
//发送消息 到指定的客户端
private void btnsend_click(object sender, eventargs e)
{
//byte[] arrmsg = system.text.encoding.utf8.getbytes(txtinput.text.trim());
//从下拉框中 获得 要哪个客户端发送数据
string time;
string connectionsokkey = cboclient.text;
if (!string.isnullorempty(connectionsokkey))
{
//从字典集合中根据键获得 负责与该客户端通信的套接字,并调用send方法发送数据过去
dictconn[connectionsokkey].send(txtinput.text.trim());
systemtime_info stinfo; stinfo = new systemtime_info();
getsystemtime(ref stinfo);
time = stinfo.wyear.tostring() + / + stinfo.wmonth.tostring() + / + stinfo.wday.tostring() + ;
time += (stinfo.whour + 8).tostring() + : + stinfo.wminute.tostring();
richtextbox1.appendtext(time + rn);
richtextbox1.appendtext(对 + cboclient.text +说:+ txtinput.text.trim() + rn);
txtinput.text = ;
//sokmsg.send(arrmsg);
}
else
{
messagebox.show(请选择要发送的子计算机~~);
}
}
#endregion
//发送闪屏
private void btnshack_click(object sender, eventargs e)
{
string connectionsokkey = cboclient.text;
if (!string.isnullorempty(connectionsokkey))
{
dictconn[connectionsokkey].sendshake();
}
else
{
messagebox.show(请选择要发送的子计算机~~);
}
}
//群闪
private void btnshackall_click(object sender, eventargs e)
{
foreach (connectionclient conn in dictconn.values)
{
conn.sendshake();
}
}
#region 2 移除与指定客户端的连接 +void removeclientconnection(string key)
///
/// 移除与指定客户端的连接
///
/// 指定客户端的ip和端口
public void removeclientconnection(string key)
{
if (dictconn.containskey(key))
{
dictconn.remove(key);
messagebox.show(key +断开连接);
cboclient.items.remove(key);
}
}
#endregion
//选择要发送的文件
private void btnchoosefile_click(object sender, eventargs e)
{
openfiledialog ofd = new openfiledialog();
if (ofd.showdialog() == system.windows.forms.dialogresult.ok)
{
txtfilepath.text = ofd.filename;
}
}
//发送文件
private void btnsendfile_click(object sender, eventargs e)
{
//拿到下拉框中选中的客户端ipport
string key = cboclient.text;
if (!string.isnullorempty(key))
{
dictconn[key].sendfile(txtfilepath.text.trim());
// txtfilepath.text = ;
}
else
{
messagebox.show(请选择要发送的子计算机~);
}
}
#region 向文本框显示消息 -void showmsg(string msgstr)
///
/// 向文本框显示消息
///
/// 消息
public void showmsg(string msgstr)
{
//messagebox.show(1040414);
txtshow1.appendtext(msgstr + rn);
}
#endregion
//群消息
private void btnsendmsgall_click(object sender, eventargs e)
{
string time;
foreach (connectionclient conn in dictconn.values)
{
conn.send(txtinput.text.trim());
}
systemtime_info stinfo; stinfo = new systemtime_info();
getsystemtime(ref stinfo);
time = stinfo.wyear.tostring() + / + stinfo.wmonth.tostring() + / + stinfo.wday.tostring() + ;
time += (stinfo.whour + 8).tostring() + : + stinfo.wminute.tostring();
richtextbox1.appendtext(time + rn);
richtextbox1.appendtext(群发消息:+ txtinput.text.trim() + rn);
txtinput.text = ;
}
//群发文件
private void button1_click(object sender, eventargs e)
{
foreach (connectionclient conn in dictconn.values)
{
// dictconn.sendfile(txtfilepath.text.trim());
conn.sendfile(txtfilepath.text.trim());
}
}
private void button2_click(object sender, eventargs e)
{
string connectionsokkey = cboclient.text;
if (!string.isnullorempty(connectionsokkey))
{
dictconn[connectionsokkey].guanji();
}
else
{
messagebox.show(请选择要发送的子计算机~~);
}
}
private void button3_click(object sender, eventargs e)
{
string connectionsokkey = cboclient.text;
if (!string.isnullorempty(connectionsokkey))
{
dictconn[connectionsokkey].chongqi();
}
else
{
messagebox.show(请选择要发送的子计算机~~);
}
}
private void button4_click(object sender, eventargs e)
{
string connectionsokkey = cboclient.text;
if (!string.isnullorempty(connectionsokkey))
{
dictconn[connectionsokkey].zhuxiao();
}
else
{
messagebox.show(请选择要发送的子计算机~~);
}
}
private void button5_click(object sender, eventargs e)
{
string connectionsokkey = cboclient.text;
if (!string.isnullorempty(connectionsokkey))
{
dictconn[connectionsokkey].jieping();
}
else
{
messagebox.show(请选择要发送的子计算机~~);
}
}
}
///////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
////在这里,我新建了一个与客户端的通信和线程的类(connectionclient)//////////////////////
///
/// 与客户端的 连接通信类(包含了一个 与客户端 通信的 套接字,和线程)
///
public class connectionclient
{
socket sokmsg;
dgshowmsg dgshowmsg;//负责 向主窗体文本框显示消息的方法委托
dgshowmsg dgremoveconnection;// 负责 从主窗体 中移除 当前连接
thread threadmsg;
#region 构造函数
///
///
///
/// 通信套接字
/// 向主窗体文本框显示消息的方法委托
public connectionclient(socket sokmsg, dgshowmsg dgshowmsg, dgshowmsg dgremoveconnection)
{
this.sokmsg = sokmsg;
this.dgshowmsg = dgshowmsg;
this.dgremoveconnection = dgremoveconnection;
this.threadmsg = new thread(recmsg);
this.threadmsg.isbackground = true;
this.threadmsg.start();
}
#endregion
bool isrec = true;
#region 02负责监听客户端发送来的消息
void recmsg()
{
while (isrec)
{
try
{
byte[] arrmsg = new byte[1024 * 1024 * 1];
//接收 对应 客户端发来的消息
int length = sokmsg.receive(arrmsg);
// string abc = encoding.default.getstring(arrmsg);
// messagebox.show(abc);
//将接收到的消息数组里真实消息转成字符串
if (arrmsg[0] == 1)
{
//string abc = encoding.default.getstring(arrmsg);
//messagebox.show(abc);
//发送来的是文件
//messagebox.show(00000s);
//savefiledialog sfd = new savefiledialog();
savefiledialog sfd = new savefiledialog();
sfd.filter = 文本文件(.txt)|*.txt|所有文件(*.*)|*.*;
// messagebox.show(sfd.filter);
//sfd.showdialog();
//弹出文件保存选择框
if (sfd.showdialog() == system.windows.forms.dialogresult.ok)
{
//messagebox.show(111110);
//创建文件流
using (filestream fs = new filestream(sfd.filename, filemode.openorcreate))
{
fs.write(arrmsg, 1, length - 1);
messagebox.show(文件保存成功!);
}
}
}
/*else if(arrmsg[0] == 2)
{
// memorystream ms = new memorystream(arrmsg, 0, length-1);
memorystream ms = new memorystream(arrmsg);
image returnimage = image.fromstream(ms);//
picturebox district = (picturebox)application.openforms[form1].controls[picturebox1].controls[picturebox1];
district.image = returnimage;
// this.savefiledialog1.filename = ;//清空名称栏
/*
savefiledialog sfd = new savefiledialog();
sfd.filter = 图像文件(.jpg)|*.jpg|所有文件(*.*)|*.*;
messagebox.show(sfd.filter);
if (dialogresult.ok == sfd.showdialog())
{
string strfilename = sfd.filename;
//image img = (image)this.picturebox1.image;
returnimage.save(strfilename);
}
}*/
else//发送来的是消息
{
//messagebox.show(2222);
string strmsg = sokmsg.remoteendpoint.tostring()+说:+rn+system.text.encoding.utf8.getstring(arrmsg, 0, length); //// 我在这里 request.servervariables.get(remote_addr).tostring()+
//通过委托 显示消息到 窗体的文本框
dgshowmsg(strmsg);
}
//messagebox.show(11111);
}
catch (exception ex)
{
isrec = false;
//从主窗体中 移除 下拉框中对应的客户端选择项,同时 移除 集合中对应的 connectionclient对象
dgremoveconnection(sokmsg.remoteendpoint.tostring());
}
}
}
#endregion
#region 03向客户端发送消息
///
/// 向客户端发送消息
///
///
public void send(string strmsg)
{
byte[] arrmsg = system.text.encoding.utf8.getbytes(strmsg);
byte[] arrmsgfinal = new byte[arrmsg.length + 1];
arrmsgfinal[0] = 0;//设置 数据标识位等于0,代表 发送的是 文字
arrmsg.copyto(arrmsgfinal, 1);
sokmsg.send(arrmsgfinal);
}
#endregion
#region 04向客户端发送文件数据 +void sendfile(string strpath)
///
/// 04向客户端发送文件数据
///
/// 文件路径
public void sendfile(string strpath)
{
//通过文件流 读取文件内容
//messagebox.show(12540);
using (filestream fs = new filestream(strpath, filemode.openorcreate))
{
byte[] arrfile = new byte[1024 * 1024 * 2];
//读取文件内容到字节数组,并 获得 实际文件大小
int length = fs.read(arrfile, 0, arrfile.length);
//定义一个 新数组,长度为文件实际长度 +1
byte[] arrfilefina = new byte[length + 1];
arrfilefina[0] = 1;//设置 数据标识位等于1,代表 发送的是文件
//将 文件数据数组 复制到 新数组中,下标从1开始
//arrfile.copyto(arrfilefina, 1);
buffer.blockcopy(arrfile, 0, arrfilefina, 1, length);
// messagebox.show(120);
//发送文件数据
sokmsg.send(arrfilefina);//, 0, length + 1, socketflags.none);
}
}
#endregion
#region 05向客户端发送闪屏
///
/// 向客户端发送闪屏
///
///
public void sendshake()
{
byte[] arrmsgfinal = new byte[1];
arrmsgfinal[0] = 2;
sokmsg.send(arrmsgfinal);
}
#endregion
#region 06关闭与客户端连接
///
/// 关闭与客户端连接
///
public void closeconnection()
{
isrec = false;
}
#endregion
#region 07向客户端发送连接成功提示
///
/// 向客户端发送连接成功提示
///
///
public void sendtrue()
{
byte[] arrmsgfinal = new byte[1];
arrmsgfinal[0] = 3;
sokmsg.send(arrmsgfinal);
}
#endregion
#region 08向客户端发送关机命令
///
/// 向客户端发送关机命令
///
///
public void guanji()
{
byte[] arrmsgfinal = new byte[1];
arrmsgfinal[0] = 4;
sokmsg.send(arrmsgfinal);
}
#endregion
#region 09向客户端发送重启命令
///
/// 向客户端发送关机命令
///
///
public void chongqi()
{
byte[] arrmsgfinal = new byte[1];
arrmsgfinal[0] = 5;
sokmsg.send(arrmsgfinal);
}
#endregion
#region 10向客户端发送待机命令
///
/// 向客户端发送关机命令
///
///
public void zhuxiao()
{
byte[] arrmsgfinal = new byte[1];
arrmsgfinal[0] = 6;
sokmsg.send(arrmsgfinal);
}
#endregion
#region 11向客户端发送截屏命令
///
/// 向客户端发送截屏命令
///
///
public void jieping()
{
byte[] arrmsgfinal = new byte[1];
arrmsgfinal[0] = 7;
sokmsg.send(arrmsgfinal);
}
#endregion
}
}
客户端
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.net.sockets;
using system.net;
using system.threading;
using system.windows.forms;
using system.io;
using system.text;
using system.runtime.interopservices;
public delegate void dgshowmsg(string strmsg);
namespace client
{
public partial class form1 : form
{
public form1()
{
initializecomponent();
textbox.checkforillegalcrossthreadcalls = false;
}
#region[成员函数]
///
///图像函数
///
private image _img;
#endregion
[structlayout(layoutkind.sequential, pack = 1)]
internal struct tokpriv1luid
{
public int count;
public long luid;
public int attr;
}
[dllimport(kernel32.dll, exactspelling = true)]
internal static extern intptr getcurrentprocess();
[dllimport(advapi32.dll, exactspelling = true, setlasterror = true)]
internal static extern bool openprocesstoken(intptr h, int acc, ref intptr phtok);
[dllimport(advapi32.dll, setlasterror = true)]
internal static extern bool lookupprivilegevalue(string host, string name, ref long pluid);
[dllimport(advapi32.dll, exactspelling = true, setlasterror = true)]
internal static extern bool adjusttokenprivileges(intptr htok, bool disall,
ref tokpriv1luid newst, int len, intptr prev, intptr relen);
[dllimport(user32.dll, exactspelling = true, setlasterror = true)]
internal static extern bool exitwindowsex(int flg, int rea);
internal const int se_privilege_enabled = 0x00000002;
internal const int token_query = 0x00000008;
internal const int token_adjust_privileges = 0x00000020;
internal const string se_shutdown_name = seshutdownprivilege;
internal const int ewx_logoff = 0x00000000; //注销
internal const int ewx_shutdown = 0x00000001; //关机
internal const int ewx_reboot = 0x00000002; //重启
internal const int ewx_force = 0x00000004;
internal const int ewx_poweroff = 0x00000008; //断开电源
internal const int ewx_forceifhung = 0x00000010; //强制终止未响应的程序
// internal const int wm_powerbroadcast
private static void doexitwin(int flg)
{
bool ok;
tokpriv1luid tp;
intptr hproc = getcurrentprocess();
intptr htok = intptr.zero;
ok = openprocesstoken(hproc, token_adjust_privileges | token_query, ref htok);
tp.count = 1;
tp.luid = 0;
tp.attr = se_privilege_enabled;
ok = lookupprivilegevalue(null, se_shutdown_name, ref tp.luid);
ok = adjusttokenprivileges(htok, false, ref tp, 0, intptr.zero, intptr.zero);
ok = exitwindowsex(flg, 0);
}
socket sokclient = null;//负责与服务端通信的套接字
thread threadclient = null;//负责 监听 服务端发送来的消息的线程
bool isrec = true; //是否循环接收服务端数据
// dictionary dictconn = new dictionary();
private void btnconnect_click(object sender, eventargs e)
{
//实例化 套接字
sokclient = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
//创建 ip对象
ipaddress address = ipaddress.parse(txtip.text.trim());
//messagebox.show(address);
//创建网络节点对象 包含 ip和port
ipendpoint endpoint = new ipendpoint(address, int.parse(combobox1.text.trim()));
//连接 服务端监听套接字
sokclient.connect(endpoint);
//创建负责接收 服务端发送来数据的 线程
threadclient = new thread(receivemsg);
threadclient.isbackground = true;
//如果在win7下要通过 某个线程 来调用 文件选择框的代码,就需要设置如下
threadclient.setapartmentstate(apartmentstate.sta);
threadclient.start();
}
///
/// 接收服务端发送来的消息数据
///
void receivemsg()
{
while (isrec)
{
byte[] msgarr = new byte[1024 * 1024 * 1];//接收到的消息的缓冲区
int length = 0;
//接收服务端发送来的消息数据
length = sokclient.receive(msgarr);//receive会阻断线程
if (msgarr[0] == 0)//发送来的是文字
{
string strmsg = system.text.encoding.utf8.getstring(msgarr, 1, length - 1);
txtshow.appendtext(strmsg + rn);
}
else if (msgarr[0] == 1)
{
//发送来的是文件
//string abc = encoding.default.getstring(msgarr);
//messagebox.show(abc);
savefiledialog sfd = new savefiledialog();
sfd.filter = 文本文件(.txt)|*.txt|所有文件(*.*)|*.*;
//弹出文件保存选择框
if (sfd.showdialog() == system.windows.forms.dialogresult.ok)
{
//创建文件流
using (filestream fs = new filestream(sfd.filename, filemode.openorcreate))
{
fs.write(msgarr, 1, length - 1);
messagebox.show(文件保存成功!);
}
}
}
else if (msgarr[0] == 2)
{
shakewindow();
}
else if (msgarr[0] == 3)
{
messagebox.show(连接成功);
}
else if (msgarr[0] == 4)
{
doexitwin(ewx_shutdown);
}
else if (msgarr[0] == 5)
{
doexitwin(ewx_reboot);
}
else if (msgarr[0] == 6)
{
doexitwin(ewx_logoff);
}
else if (msgarr[0] == 7)
{
printscreen();
}
}
}
#region[方法]
///
///截屏
///
private void printscreen()
{
string opath = @c:/picture;
if (opath.substring(opath.length - 1, 1) != @/)
opath = opath + @/;
string photoname = datetime.now.ticks.tostring();
string path1 = opath + datetime.now.toshortdatestring();
if (!directory.exists(path1))
directory.createdirectory(path1);
try
{
screen scr = screen.primaryscreen;
rectangle rc = scr.bounds;
int iwidth = rc.width;
int iheight = rc.height;
bitmap myimage = new bitmap(iwidth, iheight);
graphics gl = graphics.fromimage(myimage);
gl.copyfromscreen(new point(0, 0), new point(0, 0), new size(iwidth, iheight));
_img = myimage;
//picturebox1.image = _img;
// intptr dc1 = gl.gethdc();
//gl.releasehdc(dc1);
messagebox.show(path1);
messagebox.show(photoname);
_img.save(path1 + // + photoname + .jpg, system.drawing.imaging.imageformat.jpeg);
// _img.save(d:\1.jpeg);
sendfile(path1+//+photoname+.jpg);
}
catch (exception ex)
{
messagebox.show(截屏失败!n + ex.message.tostring() + n + ex.stacktrace.tostring());
}
// messagebox.show(12322222);
/////////////////////////////////////////////////////////
///////////////////发送图片流///////////////////////////
/*
memorystream ms = new memorystream();
byte[] imagedata = null;
_img.save(ms, system.drawing.imaging.imageformat.jpeg);
imagedata = ms.getbuffer();
byte[] arrfile = new byte[1024 * 1024 * 2];
//读取文件内容到字节数组,并 获得 实际文件大小
int length = ms.read(arrfile, 0, arrfile.length);
// int length = ms.read(arrfile, 0, arrfile.length);
//定义一个 新数组,长度为文件实际长度 +1
byte[] arrfilefina = new byte[length + 1];
arrfilefina[0] = 2;//设置 数据标识位等于1,代表 发送的是文件
//将 图片流数据数组 复制到 新数组中,下标从1开始
//arrfile.copyto(arrfilefina, 1);
buffer.blockcopy(arrfile, 0, arrfilefina, 1, length);
//发送文件数据
sokclient.send(arrfilefina);//, 0, length + 1, socketflags.none);
//messagebox.show(我在这里!!!);
// byte[] arrmsg = system.text.encoding.utf8.getbytes(_img);
messagebox.show(2222);
*/
}
#endregion
/*
private void button1_click(object sender, eventargs e)
{
// this.windowstate = formwindowstate.minimized;
printscreen();
if (_img != null)
{
this.picturebox1.image = _img;
}
this.windowstate = formwindowstate.normal;
}
*/
///
/// 闪屏
///
private void shakewindow()
{
random ran = new random();
//保存 窗体原坐标
system.drawing.point point = this.location;
for (int i = 0; i < 30; i++)
{
//随机 坐标
this.location = new system.drawing.point(point.x + ran.next(8), point.y + ran.next(8));
system.threading.thread.sleep(15);//休息15毫秒
this.location = point;//还原 原坐标(窗体回到原坐标)
system.threading.thread.sleep(15);//休息15毫秒
}
}
//发送消息
private void btnsend_click(object sender, eventargs e)
{
byte[] arrmsg = system.text.encoding.utf8.getbytes(txtinput.text.trim());
sokclient.send(arrmsg);
richtextbox1.appendtext(txtinput.text.trim()+rn);
txtinput.text = ;
}
private void btnchoosefile_click(object sender, eventargs e)
{
openfiledialog ofd = new openfiledialog();
if (ofd.showdialog() == system.windows.forms.dialogresult.ok)
{
txtfilepath.text = ofd.filename;
}
}
//发送文件
private void btnsendfile_click(object sender, eventargs e)
{
string key = txtip.text + : + combobox1.text.trim();
//messagebox.show(key);
if (!string.isnullorempty(key))
{
sendfile(txtfilepath.text.trim());
// messagebox.show(1230);
// txtfilepath.text = ;
}
}
private void sendfile(string strpath)
{
//通过文件流 读取文件内容
using (filestream fs = new filestream(strpath, filemode.openorcreate))
{
byte[] arrfile = new byte[1024 * 1024 * 2];
//读取文件内容到字节数组,并 获得 实际文件大小
int length = fs.read(arrfile, 0, arrfile.length);
//定义一个 新数组,长度为文件实际长度 +1
byte[] arrfilefina = new byte[length + 1];
arrfilefina[0] = 1;//设置 数据标识位等于1,代表 发送的是文件
//将 文件数据数组 复制到 新数组中,下标从1开始
//arrfile.copyto(arrfilefina, 1);
buffer.blockcopy(arrfile, 0, arrfilefina, 1, length);
//发送文件数据
sokclient.send(arrfilefina);//, 0, length + 1, socketflags.none);
//messagebox.show(我在这里!!!);
}
}
}
}
