zoukankan      html  css  js  c++  java
  • (关于Widows Mobile版本)关于字符编码、对象传递、文件传递、字符串传递、 TcpClient、TcpListener、 StreamWriter、StreamReader、 NetworkStream

    点击此处下载源代码

    上一期为pc版,请特别注意。

    /*
     * 在此程序中用到的字符串传递的知识、64位整数传递的知识、系统文件夹的获取的技巧、启动一个线程并在线程中访问程序控件的知识等。
     * 此程序在模拟器中调试的时候报错,但在真机中调试通过。
     * 作者:2009.10.15 (费了九牛二虎之力呀!)
    */


    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Net.Sockets;
    using System.IO;
    using System.Net;
    using SocketSample_2;

    namespace SockectSample
    {
        public partial class Form1 : Form
        {
            //listen on custom tcp port
            private const int port = 38080;

            public Form1()
            {
                InitializeComponent();
                System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ListenerThread));
                t.IsBackground = true;
                t.Name = "SocketListener";
                t.Start();

            }
            private delegate void AppendToListBoxDelegate(string newItem);
            private void AppendToListBox(string newItem)
            {
                listBox1.Items.Add(newItem);
            }

            //发送对象
            private void button_SendObj_Click(object sender, EventArgs e)
            {
                //create prospect object
                Prospect p = new Prospect();
                p.Name = "qihuaifeng";
                p.Company = "ahnu";
                p.Number = "1";

                TcpClient tc = new TcpClient();
                tc.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), port));

                NetworkStream ns = tc.GetStream();
                StreamWriter sw = new StreamWriter(ns);
                sw.AutoFlush = true;
                StreamReader sr = new StreamReader(ns);

                try
                {
                    sw.WriteLine("PROSPECT");
                    sw.WriteLine(p.ToString());
                    sw.Flush();

                    string response = sr.ReadLine();
                    switch (response)
                    {
                        case "PROSPECT_OK":
                            this.Invoke(new AppendToListBoxDelegate(AppendToListBox), new object[] { "数据写入成功!" });
                            break;
                        case "PROSPECT_ERROR":
                            this.Invoke(new AppendToListBoxDelegate(AppendToListBox), new object[] { "数据写入失败!" });
                            break;
                    }
                }
                catch (SocketException se)
                {
                    MessageBox.Show("Socket Exception trying to send: " + se.ToString());
                }
                finally
                {
                    ns.Close();
                }
            }
            //发送文件
            private void button_SendFile_Click(object sender, EventArgs e)
            {
                //pick a file
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    //only perform if file was selected
                    TcpClient tc = new TcpClient();
                    tc.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), port));
                    NetworkStream ns = tc.GetStream();

                    try
                    {
                        //send a header to show it will be followed by a binary file
                        byte[] header = System.Text.Encoding.UTF8.GetBytes("FILE\r\n");
                        ns.Write(header, 0, header.Length);

                        //send the filename
                        string filename = Path.GetFileName(openFileDialog1.FileName);
                        header = System.Text.Encoding.UTF8.GetBytes(filename + "\r\n");
                        ns.Write(header, 0, header.Length);

                        //send the file length (int64 - 8 bytes)
                        FileInfo fi = new FileInfo(openFileDialog1.FileName);
                        byte[] buffer = BitConverter.GetBytes(fi.Length);
                        ns.Write(buffer, 0, buffer.Length);

                        //特别注意,此处buffer的长度肯定是8 (以下输出样例来自MSDN)
                        /*
                            This example of the BitConverter.GetBytes( int )
                            method generates the following output.

                                         int          byte array
                                         ---          ----------
                                           0         00-00-00-00
                                          15         0F-00-00-00
                                         -15         F1-FF-FF-FF
                                     1048576         00-00-10-00
                                    -1048576         00-00-F0-FF
                                  1000000000         00-CA-9A-3B
                                 -1000000000         00-36-65-C4
                                 -2147483648         00-00-00-80
                                  2147483647         FF-FF-FF-7F
                            */


                        //send the file contents
                        FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open);
                        buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, (int)fs.Length);
                        ns.Write(buffer, 0, buffer.Length);
                        fs.Close();
                    }
                    catch (SocketException se)
                    {
                        MessageBox.Show(se.NativeErrorCode.ToString() + ": " + se.ToString());
                    }
                    finally
                    {
                        ns.Close();
                        tc.Close();
                    }
                    MessageBox.Show("文件发送完毕!");
                }

            }

            private void ListenerThread()
            {
                TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, port));
                listener.Start();

                try
                {
                    while (true)
                    {
                        this.Invoke(new AppendToListBoxDelegate(AppendToListBox), new object[] { "等待客户端连接... ..." });
                        TcpClient incomingClient = listener.AcceptTcpClient();

                        //get address of remove device
                        IPAddress senderAddress = ((IPEndPoint)incomingClient.Client.RemoteEndPoint).Address;

                        //get a stream to read from the socket
                        NetworkStream ns = incomingClient.GetStream();
                        try
                        {

                            StreamReader sr = new StreamReader(ns, System.Text.UTF8Encoding.UTF8);
                            StreamWriter sw = new StreamWriter(ns, System.Text.UTF8Encoding.UTF8);
                            sw.AutoFlush = true;

                            string operation = sr.ReadLine();
                                          
                            if (operation == "exit")
                            {
                                Application.Exit();
                                break;
                            }

                            if (operation == "PROSPECT")
                            {
                                string rawProspect = sr.ReadLine();
                                string[] fields = rawProspect.Split(',');

                                if (fields.Length == 3)
                                {
                                    sw.WriteLine("PROSPECT_OK");
                                }
                                else
                                {
                                    sw.WriteLine("PROSPECT_ERROR");
                                }

                                Prospect receivedProspect = new Prospect();
                                receivedProspect.Name = fields[0];
                                receivedProspect.Company = fields[1];
                                receivedProspect.Number = fields[2];
                                this.Invoke(new AppendToListBoxDelegate(AppendToListBox), new object[] {"接收到_PROSPECT:" + senderAddress.ToString() + " " + receivedProspect.ToString()});
                            }

                            if (operation == "FILE")
                            {
                                string filename = sr.ReadLine();
                                byte[] len = new byte[8];
                                ns.Read(len, 0, 8);
                                Int64 fileSize = BitConverter.ToInt64(len, 0);
                                FileStream fs = new FileStream(Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.Personal), filename), FileMode.CreateNew);
                                byte[] buffer = new byte[4096];
                                /* 第一种方案,考虑文件大小
                                int bytesread = ns.Read(buffer, 0, buffer.Length);
                                int totalbytesread = bytesread;
                                try
                                {
                                    do
                                    {
                                        fs.Write(buffer, 0, bytesread);
                                        bytesread = ns.Read(buffer, 0, buffer.Length);
                                        totalbytesread += bytesread;
                                    } while (totalbytesread < fileSize);
           
                                    fs.Close();
                                    this.Invoke(new AppendToListBoxDelegate(AppendToListBox), new object[] { senderAddress.ToString() + " " + filename });
                                }
                                catch
                                {
                                    MessageBox.Show("在接收文件过程中发生错误!");
                                }
                                */
                                //第二种方案,不考虑文件大小
                                try
                                {
                                    int bytesRead = 0;
                                    do
                                    {
                                        bytesRead = ns.Read(buffer, 0, 4096);
                                        fs.Write(buffer, 0, bytesRead);
                                    } while (bytesRead > 0);
                                    fs.Close();
                                }
                                catch
                                {
                                    MessageBox.Show("在接收文件过程中发生错误!");
                                }

                                //结论,以上两种方案都可以。次程序在模拟上报错,在真机上测试通过
                            }

                        }
                        catch (System.Net.Sockets.SocketException e)
                        {
                            ns.Close();
                            this.Invoke(new AppendToListBoxDelegate(AppendToListBox), new object[] { e.ErrorCode.ToString() + e.Message + " ERROR" });
                        }
                    }//end while
                }
                catch(System.Net.Sockets.SocketException e)
                {
                    MessageBox.Show(e.Message+e.ErrorCode.ToString()+"失败!" );
                }
                finally
                {
                    //stop the listener
                    listener.Stop();
                }
            }//end ListenerThread

            private void menuItem1_Click(object sender, EventArgs e)
            {
                Application.Exit();
            }

            private void button_exit_Click(object sender, EventArgs e)
            {
                TcpClient tc = new TcpClient();
                tc.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), port));

                NetworkStream ns = tc.GetStream();
                StreamWriter sw = new StreamWriter(ns);
                sw.AutoFlush = true;
                try
                {
                    sw.WriteLine("exit");
                 }
                catch (SocketException se)
                {
                    MessageBox.Show("Socket Exception trying to send: " + se.ToString());
                }
                finally
                {
                    ns.Close();
                }

            }

        }
    }

  • 相关阅读:
    网上找的Backbone.js
    关于数据结构,剑指offer上面的
    软件工程 什么叫高内聚 低耦合
    【丢失的转化率】你的宝贝,有多少人放进了购物车却没有支付?
    怎么都没人提 google 加密搜索呢? google如何稳定打开
    Mustache.js语法学习笔记
    C# POST数据到指定页面,并跳转至该页面
    将多个图片整合到一张图片中再用CSS 进行网页背景定位
    铁通、长宽网络支付时“签名失败”问题分析及解决方案  [88222001]验证签名异常:FAIL[20131101100002-142]
    jqGrid中多选
  • 原文地址:https://www.cnblogs.com/qqhfeng/p/1584019.html
Copyright © 2011-2022 走看看