使用C#进行点对点通讯和文件传输
<b>发送部分:</b>
发送咱们使用了多线程,可以同时进行多个任务,比如发送文件、发送文本等,互不影响:
发送文本方法:
private void startsendtext(string strhost,int iport,string strinfo)
{
sendtext sttext = new sendtext(strhost,iport,strinfo,new communclass.onsend(onsenddrawprogress)) ;
startthread(new threadstart(sttext.send)) ;
}
下面是他调用用到的一些方法:
开始一个线程
private void startthread(threadstart target)
{
thread dostep = new thread(target) ;
dostep.isbackground = true ;
dostep.start() ;
}
发送一部分(本文设置的是1024字节)成功后的回调方法
public void onsenddrawprogress(int itotal,int isending)
{
if (itotal != pbmain.maximum)
pbmain.maximum = itotal ;
pbmain.value = isending ;
}
因为使用的是线程,所以发送文本使用的是一个发送文本类的方法,该类如下:
public class sendtext
{
private string host ;
private int port ;
private string info ;
private communclass.onsend onsend ;
public sendtext(string strhost,int iport,string strinfo,
communclass.onsend onsend)
{
host = strhost ;
port = iport ;
info = strinfo ;
onsend = onsend ;
}
public void send()
{
socket s = null ;
try
{
s = communclass.connecttoserver(host,port) ;
communclass.writecommandtosocket(s,"sendtext") ;
communclass.writecommanddesctosocket(s,"") ;
communclass.writedynamictexttosocket(s,info,onsend) ;
}
catch (exception e)
{
messagebox.show(e.message) ;
}
finally
{
if (s != null)
s.close() ;
}
}
}//end class
这样就可以使用一个线程发送文本了。
发送文件的方法也类似:
private void startsendfile(string strhost,int iport,string strfile)
{
sendfile sffile = new sendfile(strhost,iport,strfile,this.pbmain) ;
pbmain.value = 0 ;
startthread(new threadstart(sffile.send)) ;
}
<b>发送文件的类:</b>
public class sendfile
{
private string host ;
private int port ;
private string filetosend ;
private progressbar pbar;
public sendfile(string strhost,int iport,string strfile,progressbar pbmain)
{
host = strhost ;
port = iport ;
filetosend = strfile ;
pbar = pbmain ;
}
public void send()
{
socket s = null ;
try
{
s = communclass.connecttoserver(host,port) ;
communclass.writecommandtosocket(s,"sendfile") ;
communclass.writecommanddesctosocket(s,"") ;
communclass.writefiletosocket(s,filetosend,new communclass.onsend(onsenddrawprogress)) ;
}
catch (exception e)
{
messagebox.show(e.message) ;
}
finally
{
if (s != null)
s.close() ;
}
}
public void onsenddrawprogress(int itotal,int isending)
{
if (itotal != pbar.maximum)
pbar.maximum = itotal ;
pbar.value = isending ;
}
}//end class
当然,你发送一个命令让服务器端启动一个程序(靠,这不成木马了吗?)也可以:
Tag: 点对点通讯 ,文件传输