public MyTcpListener(int port) : base(port) { } public void StopMe() { if ( this.Server != null ) { this.Server.Close(); } } }
public class Transfer { MyTcpListener tcpl;
public Transfer() { OptionsLoader ol = new OptionsLoader(); int port = 8081; if (ol.Port > 0) { port = ol.Port; } else { port = 8081; }
this.tcpl = new MyTcpListener(port); } public void TransferShutdown() { tcpl.StopMe(); }
public void ListenForPeers() { try { Encoding ASCII = Encoding.ASCII;
tcpl.Start();
while (true) { // 在有连接之前,Accept将处于阻塞状态 Socket s = tcpl.AcceptSocket(); NetworkStream DataStream = new NetworkStream(s);
String filename; Byte[] Buffer = new Byte[256]; DataStream.Read(Buffer, 0, 256); filename = Encoding.ASCII.GetString(Buffer); StringBuilder sbFileName = new StringBuilder(filename); StringBuilder sbFileName2 = sbFileName.Replace("\", "\\"); FileStream fs = new FileStream(sbFileName2.ToString(), FileMode.Open, FileAccess.Read); BinaryReader reader = new BinaryReader(fs); byte[] bytes = new byte[1024]; int read; while((read = reader.Read(bytes, 0, bytes.Length)) != 0) { DataStream.Write(bytes, 0, read); } reader.Close(); DataStream.Flush(); DataStream.Close(); } } catch(SocketException ex) { MessageBox.Show(ex.ToString()); } }
public void DownloadToClient(String server, string remotefilename, string localfilename) { try { TcpClient tcpc = new TcpClient(); Byte[] read = new Byte[1024];
OptionsLoader ol = new OptionsLoader(); int port = 0; if (ol.Port > 0) { port = ol.Port; } else { // 缺省的端口号,可以设置为使用的端口号 port = 8081; }
// 尝试与服务器连接 IPHostEntry IPHost = Dns.Resolve(server); string []aliases = IPHost.Aliases; IPAddress[] addr = IPHost.AddressList;
IPEndPoint ep = new IPEndPoint(addr[0], port); tcpc.Connect(ep); // 获得流对象 Stream s = tcpc.GetStream(); Byte[] b = Encoding.ASCII.GetBytes(remotefilename.ToCharArray()); s.Write( b, 0, b.Length ); int bytes; FileStream fs = new FileStream(localfilename, FileMode.OpenOrCreate); BinaryWriter w = new BinaryWriter(fs);
// 读取流对象,并将其转换为ASCII码 while( (bytes = s.Read(read, 0, read.Length)) != 0) { w.Write(read, 0, bytes); read = new Byte[1024]; }
tcpc.Close(); w.Close(); fs.Close(); } catch(Exception ex) { throw new Excep
免责声明: 本文仅代表作者个人观点,与爱易网无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。