本帖最后由 whble 于 2012-12-31 11:27 编辑
最近在做数据回传 老大说是采用的是socket 异步通信方式
就在最近这段时间去了解了 一下 在自己写的上位机上测试了 一下
发送数据是没有问题 但是接收数据有点不是很正常 求高手指点
首先申明
- SocketFunc socket;
- System.Action<string> ReceiveAction;
- System.Action AccessAction;
- public MainForm()
- {
- InitializeComponent();
- }
复制代码 然后mainform_load下注册进行数据回调
- private void MainForm_Load(object sender, EventArgs e)
- {
- GetIni();
- AccessAction = () =>
- {
- this.Invoke((MethodInvoker)delegate()
- {
- try
- {
- socket.Receive(ReceiveAction);
- }
- catch (Exception exp)
- {
- MessageBox.Show(exp.Message, "错误");
- }
- });
- };
- //异步接收消息回调
- ReceiveAction = msg =>
- {
- Temporary.Invoke((MethodInvoker)delegate()
- {
- Temporary.Text = msg;
- textBox1.Text = msg;
- });
- };
- NewClient();
- }
- void NewClient()
- {
- this.socket = new ClientSocket();
- try
- {
- this.socket.Access(ControlIp, this.AccessAction);
- }
- catch (Exception ecp)
- {
- MessageBox.Show(ecp.Message, "错误");
- }
- }
复制代码 SocketFunc这个类如下
- public abstract class SocketFunc
- {
- //建立连接后用这个Socket进行通信
- public Socket communicateSocket = null;
- //客户端建立连接的方式稍有不同, 子类会重载
- public abstract void Access(string IP, System.Action AccessAciton);
- public byte[] HexToByte(string hexString)
- {
- byte[] returnBytes = new byte[hexString.Length / 2];
- for (int i = 0; i < returnBytes.Length; i++)
- returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
- return returnBytes;
- }
- // 发送消息的函数
- public void Send(string message)
- {
- if (communicateSocket.Connected == false)
- {
- throw new Exception("还没有建立连接, 不能发送消息");
- }
- Byte[] msg = HexToByte(message);// Encoding.UTF8.GetBytes(message);
- communicateSocket.BeginSend(msg,0, msg.Length, SocketFlags.None,
- ar => {
- }, null);
- }
- //接受消息的函数
- public void Receive(System.Action<string> ReceiveAction)
- {
- //如果消息超过1024个字节, 收到的消息会分为(总字节长度/1024 +1)条显示
- Byte[] msg = new byte[64];
- //异步的接受消息
- communicateSocket.BeginReceive(msg, 0, msg.Length, SocketFlags.None,
- ar => {
- //对方断开连接时, 这里抛出Socket Exception
- //An existing connection was forcibly closed by the remote host
- communicateSocket.EndReceive(ar);
- ReceiveAction(Encoding.UTF8.GetString(msg).Trim('\0', ' '));
- // ReceiveAction = HexToByte(ReceiveAction);
- Receive(ReceiveAction);
- }, null);
- }
- }
- public class ClientSocket:SocketFunc
- {
- //客户端重载Access函数
- public override void Access(string IP, System.Action AccessAciton)
- {
- base.communicateSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- base.communicateSocket.Bind(new IPEndPoint(IPAddress.Any, 2001));
- //服务器的IP和端口
- IPEndPoint serverIP;
- try
- {
- serverIP = new IPEndPoint(IPAddress.Parse(IP), 2001);
- }
- catch
- {
- throw new Exception(String.Format("{0}不是一个有效的IP地址!", IP));
- }
- //客户端只用来向指定的服务器发送信息,不需要绑定本机的IP和端口,不需要监听
- try
- {
- base.communicateSocket.BeginConnect(serverIP, ar =>
- {
- AccessAciton();
- }, null);
- }
- catch
- {
- throw new Exception(string.Format("尝试连接{0}不成功!", IP));
- }
- }
- }
复制代码 这样的话就可以进行数据的发送回传
只要在按钮事件中添加
socket.Send(CMD_GoBack);
就可以发送指令
而在异步接收消息回调,也就是在Mainform_load中把数据传回来
我这里是用
Temporary.Text = " "+msg;
textBox1.Text = msg;
来接收回来的
但是现在还有点小问题
如图
就是接收的数据都不显示第一个字符
请高手指点!!!
(⊙o⊙)… 水印挡住了 第一幅图串口发送123 上位机接收到23
第二幅图串口发12 上位机接收到2
|