wp7手机要对wifi小车发送控制指令,在建立好wifi连接之后,就要用socket通信了。之前介绍了703n路由里ser2net包的强大功能(能将ttl串口信号和net信号相互转换),下位机仍然只管接收发送串口信号就行。
其实也就是在wp7和703之间建立通信,发送网络指令。
添加这两个引用,原因就不说了
using System.Net;
using System.Net.Sockets;
定义几个变量
private Socket sock = null;
private string wifiIP = string.Empty;
private int wifiPort;
private ManualResetEvent MyEvent = null;
private DnsEndPoint hostEntry;
在formload里写如下代码
wifiIP = "路由器ip地址";
wifiPort = "路由telnet端口";
//建立一个终结点对像
hostEntry = new DnsEndPoint(wifiIP, wifiPort);
//创建一个Socket对象
try
{
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
catch (Exception ex)
{
// sysInfo.Text = "与路由器连接失败";
}
if (sock != null)
{
connectsocket();
}
private void connectsocket()
{
if (sock != null)
{
SocketAsyncEventArgs connArg = new SocketAsyncEventArgs();
// 要连接的远程服务器
connArg.RemoteEndPoint = new DnsEndPoint(wifiIP, wifiPort);
// 操作完成后的回调
connArg.Completed += (sendObj, arg) =>
{
if (arg.SocketError == SocketError.Success) //连接成功
{
//Dispatcher.BeginInvoke(() => sysInfo.Text = "连接成功。");
}
else
{
Dispatcher.BeginInvoke(() =>
{
// sysInfo.Text = "连接失败,错误:" + arg.SocketError.ToString();
});
}
// 向调用线程报告操作结束
MyEvent.Set();
};
// 重置线程等待事件
MyEvent.Reset();
// sysInfo.Text = "正在连接,请等候……";
// 开始异连接
sock.ConnectAsync(connArg);
// 等待连接完成
MyEvent.WaitOne(6000);
}
}
这样与路由就建立起了连接,接下来写个发送信息的方法:
private void SendData(string data)
{
if (sock != null && sock.Connected)
{
SocketAsyncEventArgs sendArg = new SocketAsyncEventArgs();
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(data);
sendArg.SetBuffer(buffer, 0, buffer.Length);
// 发送完成后的回调
sendArg.Completed += (objSender, mArg) =>
{
// 如果操作成功
if (mArg.SocketError == SocketError.Success)
{
//Dispatcher.BeginInvoke(() => sysInfo.Text = "发送成功。");
}
else
{
Dispatcher.BeginInvoke(() =>
{
//this.sysInfo.Text = "发送失败,错误:" + mArg.SocketError.ToString();
});
}
// 报告异步操作结束
MyEvent.Set();
};
// 重置信号
MyEvent.Reset();
// Dispatcher.BeginInvoke(() => sysInfo.Text = "正在发送,请等候……");
// 异步发送
sock.SendAsync(sendArg);
// 等待操作完成
MyEvent.WaitOne(6000);
}
}