irDA数据是红外线传输,它传输方式有2种方式:
1.irComm2k(把红外模拟成为一个串口)
优点: 传输速度快。
缺点:
1.要使用别人是driver,driver还不稳定。
2.这个驱动在win7不能使用。
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using QRDecodeProj;
namespace CSharpSerialPort
{
/// <summary>
/// SerialPort
/// </summary>
public class SerialPort
{
#region API
//win32 api constants
private const uint GENERIC_READ = 0x80000000;
private const uint GENERIC_WRITE = 0x40000000;
private const int OPEN_EXISTING = 3;
private const int INVALID_HANDLE_VALUE = -1;
private const int MAXBLOCK = 4096;
private const uint PURGE_TXABORT = 0x0001; // Kill the pending/current writes to the comm port.
private const uint PURGE_RXABORT = 0x0002; // Kill the pending/current reads to the comm port.
private const uint PURGE_TXCLEAR = 0x0004; // Kill the transmit queue if there.
private const uint PURGE_RXCLEAR = 0x0008; // Kill the typeahead buffer if there.
[StructLayout(LayoutKind.Sequential)]
private struct DCB
{
//taken from c struct in platform sdk
public int DCBlength; // sizeof(DCB)
public int BaudRate; // current baud rate
public int fBinary; // binary mode, no EOF check
public int fParity; // enable parity checking
public int fOutxCtsFlow; // CTS output flow control
public int fOutxDsrFlow; // DSR output flow control
public int fDtrControl; // DTR flow control type
public int fDsrSensitivity; // DSR sensitivity
public int fTXContinueOnXoff; // XOFF continues Tx
public int fOutX; // XON/XOFF out flow control
public int fInX; // XON/XOFF in flow control
public int fErrorChar; // enable error replacement
public int fNull; // enable null stripping
public int fRtsControl; // RTS flow control
public int fAbortOnError; // abort on error
public int fDummy2; // reserved
public ushort wReserved; // not currently used
public ushort XonLim; // transmit XON threshold
public ushort XoffLim; // transmit XOFF threshold
public byte ByteSize; // number of bits/byte, 4-8
public byte Parity; // 0-4=no,odd,even,mark,space
public byte StopBits; // 0,1,2 = 1, 1.5, 2
public char XonChar; // Tx and Rx XON character
public char XoffChar; // Tx and Rx XOFF character
public char ErrorChar; // error replacement character
public char EofChar; // end of input character
public char EvtChar; // received event character
public ushort wReserved1; // reserved; do not use
}
[StructLayout(LayoutKind.Sequential)]
private struct COMMTIMEOUTS
{
public int ReadIntervalTimeout;
public int ReadTotalTimeoutMultiplier;
public int ReadTotalTimeoutConstant;
public int WriteTotalTimeoutMultiplier;
public int WriteTotalTimeoutConstant;
}
[StructLayout(LayoutKind.Sequential)]
private struct OVERLAPPED
{
public int Internal;
public int InternalHigh;
public int Offset;
public int OffsetHigh;
public int hEvent;
}
[StructLayout(LayoutKind.Sequential)]
private struct COMSTAT
{
/*public int fCtsHold;
public int fDsrHold;
public int fRlsdHold;
public int fXoffHold;
public int fXoffSent;
public int fEof;
public int fTxim;
public int fReserved;
public int cbInQue;
public int cbOutQue;*/
// Should have a reverse, i don't know why!!!!!
public int cbOutQue;
public int cbInQue;
public int fReserved;
public int fTxim;
public int fEof;
public int fXoffSent;
public int fXoffHold;
public int fRlsdHold;
public int fDsrHold;
public int fCtsHold;
}
//#if FULLFRAMEWORK
[DllImport("kernel32")]
private static extern int CreateFile(
string lpFileName, // file name
uint dwDesiredAccess, // access mode
int dwShareMode, // share mode
int lpSecurityAttributes, // SD
int dwCreationDisposition, // how to create
int dwFlagsAndAttributes, // file attributes
int hTemplateFile // handle to template file
);
//#else
// [DllImport("coredll")]
// private static extern int CreateFile(
// string lpFileName, // file name
// uint dwDesiredAccess, // access mode
// int dwShareMode, // share mode
// int lpSecurityAttributes, // SD
// int dwCreationDisposition, // how to create
// int dwFlagsAndAttributes, // file attributes
// int hTemplateFile // handle to template file
// );
//#endif
//#if FULLFRAMEWORK
[DllImport("kernel32")]
private static extern bool GetCommState(
int hFile, // handle to communications device
ref DCB lpDCB // device-control block
);
//#else
// [DllImport("coredll")]
// private static extern bool GetCommState(
// int hFile, // handle to communications device
// ref DCB lpDCB // device-control block
// );
//#endif
//#if FULLFRAMEWORK
[DllImport("kernel32")]
private static extern bool BuildCommDCB(
string lpDef, // device-control string
ref DCB lpDCB // device-control block
);
//#else
// [DllImport("coredll")]
// private static extern bool BuildCommDCB(
// string lpDef, // device-control string
// ref DCB lpDCB // device-control block
// );
//#endif
//#if FULLFRAMEWORK
[DllImport("kernel32")]
private static extern bool SetCommState(
int hFile, // handle to communications device
ref DCB lpDCB // device-control block
);
//#else
// [DllImport("coredll")]
// private static extern bool SetCommState(
// int hFile, // handle to communications device
// ref DCB lpDCB // device-control block
// );
#endif
//#if FULLFRAMEWORK
[DllImport("kernel32")]
private static extern bool GetCommTimeouts(
int hFile, // handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // time-out values
);
//#else
// [DllImport("coredll")]
// private static extern bool GetCommTimeouts(
// int hFile, // handle to comm device
// ref COMMTIMEOUTS lpCommTimeouts // time-out values
// );
//#endif
//#if FULLFRAMEWORK
[DllImport("kernel32")]
private static extern bool SetCommTimeouts(
int hFile, // handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // time-out values
);
//#else
// [DllImport("coredll")]
// private static extern bool SetCommTimeouts(
// int hFile, // handle to comm device
// ref COMMTIMEOUTS lpCommTimeouts // time-out values
// );
//#endif
//#if FULLFRAMEWORK
[DllImport("kernel32")]
private static extern bool ReadFile(
int hFile, // handle to file
byte[] lpBuffer, // data buffer
int nNumberOfBytesToRead, // number of bytes to read
ref int lpNumberOfBytesRead, // number of bytes read
ref OVERLAPPED lpOverlapped // overlapped buffer
);
//#else
// [DllImport("coredll")]
// private static extern bool ReadFile(
// int hFile, // handle to file
// byte[] lpBuffer, // data buffer
// int nNumberOfBytesToRead, // number of bytes to read
// ref int lpNumberOfBytesRead, // number of bytes read
// ref OVERLAPPED lpOverlapped // overlapped buffer
// );
//#endif
//#if FULLFRAMEWORK
[DllImport("kernel32")]
private static extern bool WriteFile(
int hFile, // handle to file
byte[] lpBuffer, // data buffer
int nNumberOfBytesToWrite, // number of bytes to write
ref int lpNumberOfBytesWritten, // number of bytes written
ref OVERLAPPED lpOverlapped // overlapped buffer
);
//#else
// [DllImport("coredll")]
// private static extern bool WriteFile(
// int hFile, // handle to file
// byte[] lpBuffer, // data buffer
// int nNumberOfBytesToWrite, // number of bytes to write
// ref int lpNumberOfBytesWritten, // number of bytes written
// ref OVERLAPPED lpOverlapped // overlapped buffer
// );
//#endif
//#if FULLFRAMEWORK
[DllImport("kernel32")]
private static extern bool CloseHandle(
int hObject // handle to object
);
//#else
// [DllImport("coredll")]
// private static extern bool CloseHandle(
// int hObject // handle to object
// );
//#endif
//#if FULLFRAMEWORK
[DllImport("kernel32")]
private static extern bool ClearCommError(
int hFile, // handle to file
ref int lpErrors,
ref COMSTAT lpStat
);
//#else
// [DllImport("coredll")]
// private static extern bool ClearCommError(
// int hFile, // handle to file
// ref int lpErrors,
// ref COMSTAT lpStat
// );
//#endif
//#if FULLFRAMEWORK
[DllImport("kernel32")]
private static extern bool PurgeComm(
int hFile, // handle to file
uint dwFlags
);
//#else
// [DllImport("coredll")]
// private static extern bool PurgeComm(
// int hFile, // handle to file
// uint dwFlags
// );
//#endif
//#if FULLFRAMEWORK
[DllImport("kernel32")]
private static extern bool SetupComm(
int hFile,
int dwInQueue,
int dwOutQueue
);
//#else
// [DllImport("coredll")]
// private static extern bool SetupComm(
// int hFile,
// int dwInQueue,
// int dwOutQueue
// );
//#endif
#endregion
// SerialPort的成员变量
private int hComm = INVALID_HANDLE_VALUE;
private bool bOpened = false;
public bool Opened
{
get
{
return bOpened;
}
}
/// <summary>
///串口的初始化函数
///lpFileName 端口名
///baudRate 波特率
///parity 校验位
///byteSize 数据位
///stopBits 停止位
/// <summary>
public bool OpenPort(string lpFileName, int baudRate, byte parity, byte byteSize, byte stopBits,bool isRead)
{
if (bOpened)
{
Common.WriteLog(0, "OpenPort error");
return false;
}
// OPEN THE COMM PORT.
if(isRead)
hComm = CreateFile(lpFileName, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
else
{
hComm = CreateFile(lpFileName, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
}
// IF THE PORT CANNOT BE OPENED, BAIL OUT.
if (hComm == INVALID_HANDLE_VALUE)
{
return false;
}
SetupComm(hComm, MAXBLOCK, MAXBLOCK);
// SET THE COMM TIMEOUTS.
COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();
GetCommTimeouts(hComm, ref ctoCommPort);
ctoCommPort.ReadIntervalTimeout = Int32.MaxValue;
ctoCommPort.ReadTotalTimeoutConstant = 1000;
ctoCommPort.ReadTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutMultiplier = -1;
ctoCommPort.WriteTotalTimeoutConstant = 1000;
SetCommTimeouts(hComm, ref ctoCommPort);
// SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
// THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST.
// IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER
// THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING.
// ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING.
DCB dcbCommPort = new DCB();
dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort);
GetCommState(hComm, ref dcbCommPort);
dcbCommPort.BaudRate = baudRate;
dcbCommPort.Parity = parity;
dcbCommPort.fBinary = 0;
dcbCommPort.fParity = 0;
dcbCommPort.ByteSize = byteSize;
dcbCommPort.StopBits = stopBits;
dcbCommPort.fOutxCtsFlow = 0;
dcbCommPort.fOutxDsrFlow = 0;
dcbCommPort.fRtsControl = 1;
dcbCommPort.fDtrControl = 1;
SetCommState(hComm, ref dcbCommPort);
PurgeComm(hComm, PURGE_RXCLEAR | PURGE_RXABORT);
PurgeComm(hComm, PURGE_TXCLEAR | PURGE_TXABORT);
bOpened = true;
return true;
}
// 关闭串口
public bool ClosePort()
{
_run = false;
if(_serialThread.IsAlive)
{
_serialThread.Abort();
}
if (hComm == INVALID_HANDLE_VALUE)
{
return false;
}
if (CloseHandle(hComm))
{
hComm = INVALID_HANDLE_VALUE;
bOpened = false;
return true;
}
else
{
return false;
}
}
// write date to port
public bool WritePort(byte[] WriteBytes, int dwLen)
{
try
{
if (hComm == INVALID_HANDLE_VALUE)
{
return false;
}
COMSTAT ComStat = new COMSTAT();
int dwErrorFlags = 0;
ClearCommError(hComm, ref dwErrorFlags, ref ComStat);
if (dwErrorFlags != 0)
PurgeComm(hComm, PURGE_TXCLEAR | PURGE_TXABORT);
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesWritten = 0;
return WriteFile(hComm, WriteBytes, dwLen, ref BytesWritten, ref ovlCommPort);
}
catch (Exception e)
{
Common.WriteLog(0, "WriteBytes error" + e.Message);
return false;
}
}
// read date from port
public int ReadPort(int NumBytes, byte[] commRead)
{
if (hComm == INVALID_HANDLE_VALUE)
{
return 0;
}
COMSTAT ComStat = new COMSTAT();
int dwErrorFlags = 0;
ClearCommError(hComm, ref dwErrorFlags, ref ComStat);
if (dwErrorFlags != 0)
{
PurgeComm(hComm, PURGE_RXCLEAR | PURGE_RXABORT);
}
if (ComStat.cbInQue > 0)
{
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesRead = 0;
ReadFile(hComm, commRead, NumBytes, ref BytesRead, ref ovlCommPort);
return BytesRead;
}
else
{
return 0;
}
}
Thread _receiveThread;
Thread _writeThread;
private Thread _serialThread;
private bool _run;
bool _bReceive;
private byte[] _oldReceiveData = new byte[10000];
private byte[] _writedata =new byte[10000];
private int _writedatalength;
public SerialPort()
{
_run = false;
}
public void Read()
{
if(OpenPort("COM5:", 4800, 0, 8, 1,true))
{
_bReceive = true;
_run = true;
_serialThread = new Thread(SerialThread);
_serialThread.Start();
}
}
public void Write(byte[] WriteBytes, int dwLen)
{
if( OpenPort("COM5:", 4800, 0, 8, 1,false))
{
_writedatalength = dwLen;
_writedata = WriteBytes;
_bReceive = false;
_run = true;
_serialThread = new Thread(SerialThread);
_serialThread.Start();
}
}
private void SerialThread()
{
byte[] bytes = new byte[10000];
while (_run)
{
if (_bReceive)
{
int length = ReadPort(10000, bytes);
Common.WriteLog(0, "ReceiveDataThread" + length.ToString());
if (length > 0 && length < 10000)
{
Common.WriteLog(0, "ReceiveDataThread" + length.ToString());
if (!BytesEquals(bytes, _oldReceiveData))
{
BytesCopy(_oldReceiveData, bytes);
ReceiveDataDelegateEvent(bytes, length);
}
}
Thread.Sleep(700);
}
else
{
bool bRet = WritePort(_writedata, _writedatalength);
Common.WriteLog(0, "WritePortThread");
Thread.Sleep(2000);
}
}
}
static bool BytesEquals(byte[] array1, byte[] array2)
{
if (array1.Length != array2.Length)
return false;
for (int i = 0; i < array1.Length; i++)
if (array1[i] != array2[i])
return false;
return true;
}
static bool BytesCopy(byte[] array1, byte[] array2)
{
for (int i = 0; i < array2.Length; i++)
array1[i] = array2[i];
return true;
}
public event ReceiveDataDelegate ReceiveDataDelegateEvent;
}
public delegate void ReceiveDataDelegate(byte[] data,int length);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;
using QRDecodeProj;
namespace SerialPortOperation
{
public class SerialPortOPs
{
private SerialPort _serialPort;
private Thread sendThread;
private Thread _receiveThread;
Byte[] _sendData;
Byte[] _readData;
int _senddatalength;
private bool _bReceive;
private bool _bSend;
/* public SerialPortOPs()
{
}
public void SerialPortOpen()
{
_serialPort.PortName = "COM5";
_serialPort.BaudRate = 9600;
_serialPort.DataBits = 8;
_serialPort.Parity = Parity.None;
_serialPort.StopBits = StopBits.One;
}
private void SendData()
{
while (_bSend)
{
try
{
Common.WriteLog(0, "senddata begin" );
_serialPort.Write(_sendData, 0, _senddatalength);
Common.WriteLog(0, "senddata end");
}
catch (Exception e )
{
Common.WriteLog(0,"senddata error"+ e.Message);
}
//MessageBox.Show("send");
Thread.Sleep(1000);
}
}
public void Send(string str)
{
_bSend = true;
SerialPortOpen();
_serialPort.Open();
Common.WriteLog(0, "senddata begin");
byte[] bytes = new byte[10];
_serialPort.Write(bytes,0,10);
Common.WriteLog(0, "senddata end");
_serialPort.Close();
// sendThread = new Thread(SendData);
// sendThread.Start();
}
public void StopToSend()
{
_bSend = false;
sendThread.Abort();
_serialPort.Close();
}
public void Receive()
{
_serialPort.Open();
/* _bReceive = true;
_receiveThread = new Thread(new ThreadStart(ReceiveData));
_receiveThread.Start();
byte[] data = Convert.FromBase64String(_serialPort.ReadLine());
string str = Encoding.Unicode.GetString(data);
MessageBox.Show(str);
_serialPort.Close();
}
public void StopToReceive()
{
_serialPort.Close();
_bReceive = false;
_receiveThread.Abort();
}
private void ReceiveData()
{
while (true&&_bReceive)
{
_readData = new Byte[_serialPort.ReadBufferSize + 1];
Byte[] readBuffer = new Byte[_serialPort.ReadBufferSize + 1];
try
{
int count = _serialPort.Read(readBuffer, 0, _serialPort.ReadBufferSize);
if (count != 0)
{
Array.Copy(readBuffer, _readData, count);
if (DataReceived != null)
{
DataReceived(_readData);
}
}
}
catch (TimeoutException) { }
Thread.Sleep(1000);
}
}
public static event ReceiveDataDelegate DataReceived;*/
// private SerialPort _serialPort;
public void InitCOM(string PortName)
{
_serialPort = new SerialPort(PortName);
_serialPort.BaudRate = 4800;
_serialPort.Parity = Parity.None;
_serialPort.StopBits = StopBits.Two;
_serialPort.Handshake = Handshake.RequestToSend;
_serialPort.ReceivedBytesThreshold = 4;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(port1_DataReceived); //DataReceived事件委托
}
private void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
StringBuilder currentline = new StringBuilder();
while (_serialPort.BytesToRead > 0)
{
char ch = (char) _serialPort.ReadByte();
currentline.Append(ch);
}
//在这里对接收到的数据进行处理
//
currentline = new StringBuilder();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
public void OpenPort()
{
try
{
_serialPort.Open();
}
catch
{
}
if (_serialPort.IsOpen)
{
Console.WriteLine("the port is opened!");
}
else
{
Console.WriteLine("failure to open the port!");
}
}
public void SendCommand(string CommandString)
{
InitCOM("COM5");
OpenPort();
/* byte[] bytes = new byte[CommandString.Length/ 2];
for (int i = 0; i < CommandString.Length-2; i += 2)
{
byte b = Convert.ToByte(CommandString.Substring(i, 2), 16);
bytes[i / 2] = b;
}*/
byte[] WriteBuffer = Encoding.ASCII.GetBytes(CommandString);
_serialPort.Write(WriteBuffer, 0, WriteBuffer.Length);
_serialPort.Close();
}
}
public delegate void ReceiveDataDelegate(byte[] data);
2使用socket通讯
优点:传输比较稳定
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace QRDecodeProj.IrDA
{
class irDASocket
{
private static irDASocketdll.irDACallBack irDAsendCallback = new irDASocketdll.irDACallBack(SendCallBack);
private static irDASocketdll.irDACallBack irDAReceiveCallback = new irDASocketdll.irDACallBack(ReceiveCallBack);
public static Thread _receiverThread;
public static Thread _sendThread;
private static byte[] _senddata;
private static int _length;
private static void ReceiveCallBack(EventType eventtype, IntPtr data, int length)
{
switch (eventtype)
{
case EventType.SOCKET_RECEIVE_DATA:
{
//string str = new string(data);
// MessageBox.Show("receive the package");
Form1._irDAMessageForm.CloseMesssage();
Common.WriteLog(0, "receive the package" + length.ToString());
byte[] managedArray2 = new byte[length];
Marshal.Copy(data, managedArray2, 0, length);
ReceiveDataDelegateEvent(managedArray2, length);
break;
}
default:
Form1._irDAMessageForm.CloseMesssage();
MessageBox.Show("receive error,please click receive button again.");
break;
}
}
private static void SendCallBack(EventType eventType, IntPtr data, int length)
{
switch (eventType)
{
case EventType.SOCKET_SEND_SUCCEED:
Form1._irDAMessageForm.CloseMesssage();
break;
default:
{
// Thread.Sleep();
runSender(_senddata,_length);
Common.WriteLog(0, "irDA send again");
}
break;
}
}
public static void runReceiver()
{
_receiverThread = new Thread(new ThreadStart(irDAReceive));
_receiverThread.Start();
}
private static void irDAReceive()
{
irDASocketdll.ReceiveDatabyirDA(irDAReceiveCallback);
}
public static void runSender(byte[] data, int length)
{
_senddata = data;
_length = length;
_sendThread = new Thread(new ThreadStart(irDASend));
_sendThread.Start();
}
private static void irDASend()
{
irDASocketdll.SendDatabyirDA(_senddata, _length, irDAsendCallback);
}
public static event ReceiveDataDelegate ReceiveDataDelegateEvent;
}
public delegate void ReceiveDataDelegate(byte[] data,int length);
}
dll代码:
#include "stdafx.h"
typedef void (_stdcall *DllCallback)(int msgID,char* msg,int length);
void Callback_Sender(int msgID,char* msg,int length);
DllCallback m_CallbackSender;
DllCallback m_CallbackReader;
#include "af_irda.h"
#include <stdio.h>
#pragma comment (lib, "WS2_32.Lib")
//#include <afx.h>
#include <winsock.h>
#include <wsipx.h>
#include <wsnwlink.h>
#include <stdio.h>
typedef enum EventType_E {
NODEFINE_ERROR,
INIT_SOCKET_ERROR,
GET_SOCKETOPT_ERROR,
OUT_NUMRETYR_ERROR,
SOCKET_CONNECT_ERROR,
SOCKET_SEND_ERROR,
SOCKET_SEND_SUCCEED,
//receive
SOCKET_BIND_ERROR,
SOCKET_LISTEN_ERROR,
SOCKET_ACCEPT_ERROR,
SOCKET_RECV_ERROR,
SOCKET_RECEIVE_DATA,
} EventType;
const int NUMRETYR = 5;
EventType m_sendErrorType;
EventType m_receiverErrorType;
bool LogFile(const char *szErrMsg, const char *szFileName)
{
//CTime tCurrentTime = CTime::GetCurrentTime() ;
FILE *fp = NULL;
/*if((fp = _tfopen("c://error.log", "a")) == NULL)
{
//LogMsg("打开记录文件失败。") ;
return FALSE;
}
_tprintf(fp,"%s/n" szErrMsg);
fclose(fp); */
return TRUE;
}
UINT Sender(char* sendData,int length);
UINT Receiver(char* receive, int &length);
extern "C" _declspec(dllexport) void SendDatabyirDA(char* sendData, int len,DllCallback Callback_Sender)
{
m_sendErrorType =NODEFINE_ERROR;
m_CallbackSender = Callback_Sender;
if(Sender(sendData,len))
m_sendErrorType =SOCKET_SEND_SUCCEED;
if (m_sendErrorType != NODEFINE_ERROR)
{
m_CallbackSender(m_sendErrorType,NULL,0);
}
else
{
LogFile(NULL,"send error");
}
}
extern "C" _declspec(dllexport) VOID ReceiveDatabyirDA(DllCallback Callback_Reader)
{
m_CallbackReader = Callback_Reader;
char szServerA[3000];
int length;
if(Receiver(szServerA,length))
{
m_CallbackReader(m_receiverErrorType,szServerA,length);
}
else
{
m_CallbackReader(m_receiverErrorType,NULL,0);
}
}
void ErrOut()
{
LPVOID lpMsgBuf;
DWORD errCode=GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
errCode,
MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL);
//CString str((LPTSTR)lpMsgBuf);
// Free the buffer.
LocalFree( lpMsgBuf );
}
UINT Sender(char* sendData,int length)
{
WSADATA wsaData;
SOCKET sock; // Socket bound to the server
DEVICELIST devList; // Device list
SOCKADDR_IRDA address = {AF_IRDA, 0, 0, 0, 0, "IRServer"};
// Specifies the server socket address
int iCount = 0, // Number of retries
index = 0, // Integer index
iReturn, // Return value of recv function
iDevListLen = sizeof (devList);
// Size of the device list
char szClientA[100]; // ASCII string
WSAStartup(MAKEWORD(2,2),&wsaData);
// Create a socket that is bound to the server.
if ((sock = socket (AF_IRDA, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
ErrOut();
m_sendErrorType = INIT_SOCKET_ERROR;
return FALSE;
}
// Initialize the number of devices to zero.
devList.numDevice = 0;
while (devList.numDevice == 0 && iCount <= NUMRETYR)
{
// Retrieve the socket option.
if (getsockopt (sock, SOL_IRLMP, IRLMP_ENUMDEVICES,
(char *)&devList, &iDevListLen) == SOCKET_ERROR)
{
m_sendErrorType = GET_SOCKETOPT_ERROR;
closesocket (sock);
return FALSE;
}
iCount++;
Sleep (100);
}
if (iCount > NUMRETYR)
{
m_sendErrorType = OUT_NUMRETYR_ERROR;
closesocket (sock);
return FALSE;
}
// Get the server socket address.
for (index = 0; index <= 3; index++)
{
address.irdaDeviceID[index] = devList.Device[0].irdaDeviceID[index];
}
// Establish a connection to the socket.
if (connect (sock, (struct sockaddr *)&address,
sizeof (SOCKADDR_IRDA)) == SOCKET_ERROR)
{
m_sendErrorType = SOCKET_CONNECT_ERROR;
closesocket (sock);
return FALSE;
}
// Send a string from the client socket to the server socket.
if (send (sock, sendData, length, 0)
== SOCKET_ERROR)
{
closesocket (sock);
WSACleanup();
m_sendErrorType = SOCKET_SEND_ERROR;
return FALSE;
}
closesocket (sock);
WSACleanup();
return TRUE;
}
UINT Receiver(char* receive, int &length)
{
WSADATA wsaData;
SOCKET ServerSock, // IR socket bound to the server
ClientSock; // IR socket bound to the client
SOCKADDR_IRDA address = {AF_IRDA, 0, 0, 0, 0, "IRServer"};
// Specifies the server socket address
int index = 0, // Integer index
iReturn; // Return value of recv function
char szServerA[3000]; // ASCII string
WSAStartup(MAKEWORD(2,2),&wsaData);
// Create a socket bound to the server.
if ((ServerSock = socket (AF_IRDA, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
m_receiverErrorType = INIT_SOCKET_ERROR;
return FALSE;
}
// Associate the server socket address with the server socket.
if (bind (ServerSock, (struct sockaddr *)&address, sizeof (address))
== SOCKET_ERROR)
{
m_receiverErrorType = SOCKET_BIND_ERROR;
closesocket (ServerSock);
return FALSE;
}
// Establish a socket to listen for incoming connections.
if (listen (ServerSock, 2) == SOCKET_ERROR)
{
m_receiverErrorType = SOCKET_LISTEN_ERROR;
closesocket (ServerSock);
return FALSE;
}
// Accept a connection on the socket.
if ((ClientSock = accept (ServerSock, 0, 0)) == INVALID_SOCKET)
{
m_receiverErrorType = SOCKET_ACCEPT_ERROR;
closesocket (ServerSock);
return FALSE;
}
// Stop listening for connections from clients.
closesocket (ServerSock);
Sleep(300);
iReturn = recv (ClientSock, receive, 3000, 0);
// Check if there is any data received. If there is, display it.
if (iReturn == SOCKET_ERROR)
{
//SOCKET_ACCEPT_ERROR
//ErrOut();
m_receiverErrorType = SOCKET_RECV_ERROR;
closesocket (ClientSock);
WSACleanup();
return FALSE;
}
else if (iReturn == 0)
{
//CString str("Finished receiving data/n");
//MessageBox (NULL, str, TEXT("server"),MB_OK);
//printf("Finished receiving data/n");
closesocket (ClientSock);
WSACleanup();
return FALSE;
}
else
{
/*CString str(szServerA);
// str.Format(_T("Received From Client:%s/n"),szServerA);
MessageBox (NULL, str, TEXT("server"),MB_OK);*/
m_receiverErrorType =SOCKET_RECEIVE_DATA;
length = iReturn;
closesocket (ClientSock);
WSACleanup();
return TRUE;
}
// Close the client and server sockets.
closesocket (ClientSock);
WSACleanup();
return TRUE;
}