|
Posted on
2008-11-06 22:05
codingsilence
阅读( 175)
评论()
编辑
收藏
举报
- private string path = "F://SmartMovie.EXE";
- private Socket s;
- private void listen()
- {
- string ip = "127.0.0.1";
- IPAddress[] ih = Dns.GetHostAddresses(ip);
- IPAddress newip = ih[0];
- int port = 6789;
- IPEndPoint Conncet = new IPEndPoint(newip, port);
- s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- try
- {
- s.Connect(Conncet);
- if (s.Connected)
- {
- Console.WriteLine("连接成功");
- Thread t = new Thread(new ThreadStart(set));
- t.Start();
- Console.WriteLine("发送完毕")
- }
- }
- catch(NullReferenceException e)
- {
- Console.WriteLine("{0}",e);
- }
- private void set()
- {
- Console.WriteLine("开始发送数据");
- byte[] b = new byte[10000000];
- FileStream file = File.Open(path, FileMode.Open,FileAccess.Read);
- int start = 0;
- int end = (int)file.Length;
- try
- {
- while (end != 0)
- {
- int count = file.Read(b, start, end);
- start += count;
- end -= count;
- }
- while (start != 0)
- {
- int n = s.Send(b, end, start, SocketFlags.None);
- end += n;
- start -= n;
- }
-
- file.Close();
- s.Close();
- }
- catch (NullReferenceException e)
- {
- Console.WriteLine("{0}", e);
- }
- }
- 这样文件发送的模型就实现了
- 接下去实现文件的接收,首先要确定对方发送文件的长度,其实上面的那段还要加入发送文件长度的功能,实现很简单,就是发送int变量end ,然后要求接收代码返回一个Boolean确定是否发送,这里为了更简明的说清楚原理并没有实现
- private void get()
- {
- string path = "G://da.exe";
- FileStream file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
- TcpListener listen = new TcpListener(6789);
- Socket s1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- try
- {
- listen.Start();
- s1 = listen.AcceptSocket();
- byte[] data = new byte[10000000];
- int longer = data.Length;
- int start = 0;
- int mid = 0;
- if (s1.Connected)
- {
- Console.WriteLine("连接成功");
- int count = s1.Receive(data, start, longer, SocketFlags.None);
- mid += count;
- longer -= mid;
- while (count != 0)
- {
- count = s1.Receive(data, mid, longer, SocketFlags.None);
- mid += count;
- longer -= mid;
- }
- file.Write(data, 0, 1214134);
- s1.Close();
- file.Close();
- }
- }
- catch(NullReferenceException e)
- {
- Console.WriteLine("{0}",e);
- }
- }
|