天天看點

黑馬程式員--套接之區域網路聊天用戶端(待續)

------- Windows Phone 7手機開發、.Net教育訓練、期待與您交流! -------

用戶端的socket  

1.必須制定要連接配接的服務端位址和接口 

2.通過建立一個socket對象來初始化一個到伺服器端的TCP連接配接。

System.Net 命名空間為目前網絡上使用的多種協定提供了簡單的程式設計接口。

System.Net.Sockets 命名空間為需要嚴密控制網絡通路的開發人員提供了 Windows Sockets (Winsock) 接口的托管實作。

是以要先添加這兩個命名空間。

 public Form1()

        {

            InitializeComponent();

            TextBox.CheckForIllegalCrossThreadCalls = false;//關閉微軟對跨線程的檢查

        }

Thread threadClient = null;

        private void textBox3_TextChanged(object sender, EventArgs e)

        {

        }

        Socket socketClient = null;

        private void btnConnect_Click(object sender, EventArgs e)

        {  

                // 獲得文本框中的IP位址對象

            IPAddress address = IPAddress.Parse(txtIP.Text.Trim());

                //建立包含IP和Port的網絡節點對象

            IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));

            //建立服務端負責監聽的套接字,參數(使用IP4尋址協定,使用流式連接配接,使用TCP協定傳輸資料。

             socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // 将負責監聽的套接字綁定到唯一的IP和端口上

            socketClient.Connect(endpoint);

                 //線程化

            threadClient = new Thread(RecMsg);

            threadClient.IsBackground = true;

            threadClient.Start();

            //byte[]arrMsgRec=new byte[1024*1024*2];

            //socketClient.Receive(arrMsgRec);

            //string strMsgRec = System.Text.Encoding.UTF8.GetString(arrMsgRec);

            //ShowMsg(strMsgRec);

        }

        void RecMsg()

        {

            while (true)

            {   //定義一個接受用的緩存區、(2M)

                byte[] arrMsgRec = new byte[1024 * 1024 * 2];

               // 将接收到的資料存入arrMsgRec數組中

                int length=socketClient.Receive(arrMsgRec);

                //此時是将數組所有的元素都轉化成字元串,而真正接受的隻有幾個字元而已。

                string strMsgRec = System.Text.Encoding.UTF8.GetString(arrMsgRec,0,length);

                ShowMsg(strMsgRec);

            }

        }

           //向伺服器發送文本消息  

        private void btnSendMsg_Click(object sender, EventArgs e)

        {

            string strMsg = txtMsgSend.Text.Trim();

                     //将字元串轉成友善網絡傳送的二進制資料

            byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg);

            byte[] arrMsgSend = new byte[arrMsg.Length + 1];

            arrMsgSend[0] = 0;//設定辨別位,0代表發送的是消息

            Buffer.BlockCopy(arrMsg, 0, arrMsgSend, 1, arrMsg.Length);

            socketClient.Send(arrMsgSend);

            ShowMsg("我說:" + strMsg);

        }

        #region 在窗體文本框中顯示消息--void ShowMsg

        void ShowMsg(string msg)

        {

            txtMsg.AppendText(msg + "\r\n");

        } 

        #endregion

        #region 選擇要發送的檔案--void btnChooseFile_Click

        //選擇要發送的檔案

        private void btnChooseFile_Click(object sender, EventArgs e)

        {

            OpenFileDialog ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)

            {

                txtFilePath.Text = ofd.FileName;

            }

        }

        #endregion

        //向服務端發送檔案

        private void btnSendFile_Click(object sender, EventArgs e)

        {    

                    //用檔案流打開使用者選擇的檔案

            using (FileStream fs = new FileStream(txtFilePath.Text, FileMode.Open))

            {

                byte[] arrFile = new byte[1024 * 1024 * 2];//定義一個2兆的數組緩存區

                    //将檔案資料讀到數組arrFile中,并獲得讀取的真實資料長度

                int length=fs.Read(arrFile, 0, arrFile.Length);

                byte[] arrFileSend = new byte[length + 1];

                arrFileSend[0] = 1;//代表發送的是檔案

                      //for (int i=0;i<length;i++)

                     //{

                    //    arrFileSend[i + 1] = arrFile[i];

                    //}

                    //将arrFile中的元素從0開始拷貝到arrFileSend中的第一個位置開始存放,存放length個元素。

                Buffer.BlockCopy(arrFile, 0, arrFileSend, 1, length);

                   //發送包含了辨別位的新資料數組到服務端。

                socketClient.Send(arrFileSend);

                // 完全拷貝   arrFile.CopyTo(arrFileSend, length);

            }

        }

------- Windows Phone 7手機開發、.Net教育訓練、期待與您交流! -------