Windows Mobile Socket 通信

       本周上半周的任务是看看怎么让Windows Mobile与基站间进行移动通信(用Socket实现)。我上网查到一个客户端一个服务器端的一套程序,但是遇到的问题是:模拟器只能执行一个程序,两个程序无法同事运行。于是我问了经理这个问题,经理说不对,我们要做的是手机与基站的通信(客户端),而不是手机与手机间的通信(一客一服)。

       大致明白了这个任务的意思,我开始看仅有客户端的Socket通信程序。我找到了许多程序,不过大致差不多,以下摘录其中一个Socket客户端程序中的核心方法:

public static void StartClient()
       {
        byte[] bytes = new byte[1024];

       try {
           IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
           IPAddress ipAddress = ipHostInfo.AddressList[0];
           IPEndPoint remoteEP = new IPEndPoint(ipAddress,80);

           Socket sender = new SocketAddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp );

           try {
               sender.Connect(remoteEP);

               MessageBox.Show("Socket connected to " + sender.RemoteEndPoint.ToString());
               // Encode the data string into a byte array.
               byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");

               // Send the data through the socket.
               int bytesSent = sender.Send(msg);

               // Receive the response from the remote device.
               int bytesRec = sender.Receive(bytes);

               MessageBox.Show("Echoed test = " + Encoding.ASCII.GetString(bytes, 0, bytesRec));
               // Release the socket.
               sender.Shutdown(SocketShutdown.Both);
               sender.Close();
           } catch (ArgumentNullException ane) {
               MessageBox.Show("ArgumentNullException : " + ane.ToString());
           } catch (SocketException se) {
               MessageBox.Show("SocketException : " + se.ToString());
           } catch (Exception e) {
               MessageBox.Show("Unexpected exception : " + e.ToString());
           }

       }
       catch (Exception e)
       {
           MessageBox.Show(e.ToString());
        }
   }

       其中关键的对象为红色,关键的方法为粉色,关键的类为浅蓝色。整个程序最关键的一句是Socket send=new Socket(……),其中的3个参数为Socket通信做了明确规定。连接时用Connect方法调用参数IPEndPoint的对象,而该对象又包含了ipaddress和端口号两个参数(我认为这句是程序的另一个关键点)。之后则执行send、receive、shutdown、close等方法完成通信。

       总的来说,网上Socket程序都大同小异,由此可见,Socket通信的程序是有一定的步骤和规范的,具体编程时只需稍作修改即可。

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s