我有一个红外遥控器,我想用我的 PPC 替换它。我的 Mitac P550 有一个红外串行端口,但我不知道如何检索和重新发送字节序列.....这是否可以使用 .net 的 SerialPort 组件获取数据?
谢谢
我有一个红外遥控器,我想用我的 PPC 替换它。我的 Mitac P550 有一个红外串行端口,但我不知道如何检索和重新发送字节序列.....这是否可以使用 .net 的 SerialPort 组件获取数据?
谢谢
您需要编写两 (2) 个方法并将它们安装在通信的每一端:发送和接收。
一个通用的发送例程将向某个在给定端口号上监听的主机发送一条消息。这是一个简单的例子:
public static void Send(string message, string host, int port) {
if (!String.IsNullOrEmpty(message)) {
if (port < 80) {
port = DEF_PORT;
}
Byte[] data = Encoding.ASCII.GetBytes(message);
using (var client = new TcpClient(host, port)) {
var stream = client.GetStream();
stream.Write(data, 0, data.Length);
stream.Close();
client.Close();
}
}
}
一个通用的Receive例程需要知道要监听的端口号,并且应该返回它接收到的数据。这是一个简单的例子:
public static string Receive(int port) {
string data = null;
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
using (var client = listener.AcceptTcpClient()) { // waits until data is avaiable
int MAX = client.ReceiveBufferSize;
var stream = client.GetStream();
Byte[] buffer = new Byte[MAX];
int len = stream.Read(buffer, 0, MAX);
if (0 < len) {
data = Encoding.UTF8.GetString(buffer, 0, len);
}
stream.Close();
client.Close();
}
return data;
}
这是我用于此的完整类代码:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace AcpMobile5 {
class TestClass1 : Form {
public const int DEF_PORT = 8000;
private static TcpListener listener;
public static string Receive(int port) {
string data = null;
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
using (var client = listener.AcceptTcpClient()) { // waits until data is avaiable
int MAX = client.ReceiveBufferSize;
var stream = client.GetStream();
Byte[] buffer = new Byte[MAX];
int len = stream.Read(buffer, 0, MAX);
if (0 < len) {
data = Encoding.UTF8.GetString(buffer, 0, len);
}
stream.Close();
client.Close();
}
return data;
}
public static void Send(string message, string host, int port) {
if (!String.IsNullOrEmpty(message)) {
if (port < 80) {
port = DEF_PORT;
}
Byte[] data = Encoding.ASCII.GetBytes(message);
using (var client = new TcpClient(host, port)) {
var stream = client.GetStream();
stream.Write(data, 0, data.Length);
stream.Close();
client.Close();
}
}
}
}
}