Form1.cs
上传用户:linger1010
上传日期:2008-12-08
资源大小:561k
文件大小:3k
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- using System.Net;
- using System.Net.Sockets;
- using System.IO;
- namespace Sender
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- IrDAClient irClient = new IrDAClient();
- //定制服务的名称
- string irServiceName = "IrDATest";
- IrDADeviceInfo[] irDevices;
- int buffersize = 256;
- // 首先查找红外网络里面的设备
- irDevices = irClient.DiscoverDevices(2);
- // 显示找到的第一个设备
- if ((irDevices.Length == 0))
- {
- MessageBox.Show("No remote infrared devices found.");
- return;
- }
- try
- {
- IrDAEndPoint irEndP =
- new IrDAEndPoint(irDevices[0].DeviceID, irServiceName);
- IrDAListener irListen = new IrDAListener(irEndP);
- irListen.Start();
- irClient = irListen.AcceptIrDAClient();
- MessageBox.Show("Connected!");
- }
- catch (SocketException exSoc)
- {
- MessageBox.Show(("Couldn't listen on service "
- + (irServiceName + (": " + exSoc.ErrorCode))));
- }
- // 打开一个文件用于发送
- Stream fs;
- try
- {
- //请首先在设备的My Documents文件夹下面放置一个send.txt文件用于发送
- fs = new FileStream(".\My Documents\send.txt", FileMode.Open);
- }
- catch (Exception exFile)
- {
- MessageBox.Show(("Cannot open " + exFile.ToString()));
- return;
- }
- // 获得IrDAClient对象的数据流
- Stream baseStream = irClient.GetStream();
- // 首先获得这个文件的长度
- byte[] length = BitConverter.GetBytes(fs.Length);
- //把这个文件的长度写到流中去
- baseStream.Write(length, 0, length.Length);
- // 建立缓冲区用于读取文件
- byte[] buffer = new byte[buffersize];
- int fileLength = (int)fs.Length;
- try
- {
- // 将文件流读入IrDAClient的数据流
- while ((fileLength > 0))
- {
- Int64 numRead = fs.Read(buffer, 0, buffer.Length);
- baseStream.Write(buffer, 0, Convert.ToInt32(numRead));
- fileLength = (fileLength - Convert.ToInt32(numRead));
- }
- MessageBox.Show("File sent");
- }
- catch (Exception exSend)
- {
- MessageBox.Show(exSend.Message);
- }
- //关闭文件流,以及IrDAClient的数据流。最后关闭IrDAClient对象。
- fs.Close();
- baseStream.Close();
- irClient.Close();
- }
- }
- }