1

我正在开发一个 WinCE 应用程序 (.Net 3.5),它允许通过 TCPIP、串行端口和 USB 连接到终端。

TCPIP 和串行端口已完成,但 USB 有问题。由于客户端需要查看 USB 上的证明可以做到,我们需要证明我们可以通过 ActiveSync 发送 Hex 命令。

我用谷歌搜索了一段时间,发现 ActiveSync/WMDC 将提供 IP 以允许相互连接。问题是我无法通过 ActiveSync/WMDC 通过 C# 套接字从 PC ping 或连接到 WinCE。

我唯一知道的是,连接到 PC 时我的 WinCE IP 是:
IP 地址:192.168.55.101
子网掩码:255.255.255.0
默认网关:192.168.55.100
主 DNS:127.0.0.1

下面是我用来允许来自 ActiveSync 的所有连接的 WinCE 服务器代码。我正在重用我的 TCPIP 代码来连接到 ActiveSync。

_listener.Bind(new IPEndPoint(IPAddress.Any, _port));             
_listener.Listen(100);
_listener.BeginAccept(ConnectionReady, null);

有什么我错过了允许彼此联系的东西吗?提前致谢。

4

1 回答 1

2

似乎它是可行的,但不是直截了当的方式。

通常我们将PC设置为Server,而WinCE设置为Slave。在这种情况下,它是倒退的。WinCE 将是主机,而 PC 将是从机。

下面是我用来声明和启动连接的代码:

        private void SetUSBSerialPort()
        {
            try
            {
                usbSerialPort = new USBSerialPort(config.terminal_tcpip_port);
                usbSerialPort.OnReceiveData += new USBSerialPort.EventOnReceiveData(usbSerialPort_OnReceiveData);
                usbSerialPort.Start();
            }
            catch (Exception ex)
            {

            }
        }

下面是我用来通过 ActiveSync 连接 PC 和 WinCE 的类:

public class ConnectionStateUSB
    {
        internal Socket _conn;
        //internal TcpServiceProvider _provider;
        internal byte[] _buffer;

        /// <SUMMARY>
        /// Tells you the IP Address of the remote host.
        /// </SUMMARY>
        public EndPoint RemoteEndPoint
        {
            get { return _conn.RemoteEndPoint; }
        }

        /// <SUMMARY>
        /// Returns the number of bytes waiting to be read.
        /// </SUMMARY>
        public int AvailableData
        {
            get { return _conn.Available; }
        }

        /// <SUMMARY>
        /// Tells you if the socket is connected.
        /// </SUMMARY>
        public bool Connected
        {
            get { return _conn.Connected; }
        }

        /// <SUMMARY>
        /// Reads data on the socket, returns the number of bytes read.
        /// </SUMMARY>
        public int Read(byte[] buffer, int offset, int count)
        {
            try
            {
                if (_conn.Available > 0)
                    return _conn.Receive(buffer, offset, count, SocketFlags.None);
                else return 0;
            }
            catch
            {
                return 0;
            }
        }

        /// <SUMMARY>
        /// Sends Data to the remote host.
        /// </SUMMARY>
        public bool Write(byte[] buffer, int offset, int count)
        {
            try
            {
                _conn.Send(buffer, offset, count, SocketFlags.None);
                return true;
            }
            catch
            {
                return false;
            }
        }


        /// <SUMMARY>
        /// Ends connection with the remote host.
        /// </SUMMARY>
        public void EndConnection()
        {
            if (_conn != null && _conn.Connected)
            {
                _conn.Shutdown(SocketShutdown.Both);
                _conn.Close();
            }
        }
    }

    class USBSerialPort
    {
        Socket newsock;
        Socket client;
        int port;
        IPAddress ipaddress;
        private AsyncCallback ConnectionReady;
        private AsyncCallback AcceptConnection;
        private AsyncCallback ReceivedDataReady;
        private ConnectionStateUSB currentST;
        public bool IsConnected = false;

        public USBSerialPort(int _port)
        {
            port = _port;
            //ConnectionReady = new AsyncCallback(ConnectionReady_Handler);
            //AcceptConnection = new AsyncCallback(AcceptConnection_Handler);
            //ReceivedDataReady = new AsyncCallback(ReceivedDataReady_Handler);
        }

        public void Start()
        {            
            try
            {
                ipaddress = Dns.GetHostEntry("ppp_peer").AddressList[0];
                newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint iep = new IPEndPoint(ipaddress, port);
                newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
            }
            catch (Exception ex)
            {
                throw ex;
                this.Stop();
            }
            finally
            {
                //net_stream = null;
                //tcp_client = null;
            }
        }

        void Connected(IAsyncResult iar)
        {            
            try
            {
                client = (Socket)iar.AsyncState;
                client.EndConnect(iar);

                ConnectionStateUSB st = new ConnectionStateUSB();
                st._conn = client;
                st._buffer = new byte[4];
                //Queue the rest of the job to be executed latter
                //ThreadPool.QueueUserWorkItem(AcceptConnection, st);
                currentST = st;
                //conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();
                if (client.Connected)
                    client.BeginReceive(st._buffer, 0, 0, SocketFlags.None,
                                  new AsyncCallback(ReceiveData), st);                
            }
            catch (SocketException e)
            {
                IsConnected = false;
                //conStatus.Text = "Error connecting";
            }
            catch (Exception ex)
            {
                IsConnected = false;
            }
        }

        void ReceiveData(IAsyncResult iar)
        {
            try
            {
                ConnectionStateUSB remote = (ConnectionStateUSB)iar.AsyncState;
                remote._conn.EndReceive(iar);
                try
                {                    
                    this.OnReceiveData(remote);
                    IsConnected = true;
                }
                catch (Exception ex)
                {
                    IsConnected = false;
                }
                //int recv = remote.EndReceive(iar);
                //string stringData = Encoding.ASCII.GetString(data, 0, recv);
                //results.Items.Add(stringData);
                if (remote.Connected)
                    remote._conn.BeginReceive(remote._buffer, 0, 0, SocketFlags.None,
                                  new AsyncCallback(ReceiveData), remote);
            }
            catch (Exception ex)
            {
                this.Stop();
            }
        }

        public void SendData(byte[] data)
        {
            try
            {
                bool a = currentST.Write(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                IsConnected = false;
                MessageBox.Show("Error!\n" + ex.Message + "\n" + ex.StackTrace);
            }
        }

        public void SendData(string data)
        {
            try
            {
                byte[] msg = Encoding.UTF8.GetBytes(data + Convert.ToChar(Convert.ToByte(3)));
                bool a = currentST.Write(msg, 0, msg.Length);
                msg = null;
            }
            catch (Exception ex)
            {
                IsConnected = false;
                MessageBox.Show("Error!\n" + ex.Message + "\n" + ex.StackTrace);
            }
        }


        /// <SUMMARY>
        /// Shutsdown the server
        /// </SUMMARY>
        public void Stop()
        {
            //lock (this)
            //{
                if (newsock != null)
                    newsock.Close();
                if (client != null)
                    client.Close();
                if (currentST != null)
                {
                    currentST._conn.Close();
                    currentST = null;
                }
                IsConnected = false;
            //}
        }

        /// <SUMMARY>
        /// Gets executed when the server accepts a new connection.
        /// </SUMMARY>
        public delegate void EventOnAcceptConnection(ConnectionStateUSB socket);
        public event EventOnAcceptConnection OnAcceptConnection;

        /// <SUMMARY>
        /// Gets executed when the server detects incoming data.
        /// This method is called only if OnAcceptConnection has already finished.
        /// </SUMMARY>
        public delegate void EventOnReceiveData(ConnectionStateUSB socket);
        public event EventOnReceiveData OnReceiveData;

        /// <SUMMARY>
        /// Gets executed when the server needs to shutdown the connection.
        /// </SUMMARY>
        public delegate void EventOnDropConnection(ConnectionStateUSB socket);
        public event EventOnDropConnection OnDropConnection;
    }

希望这有帮助。

于 2013-09-18T08:08:07.687 回答