天天看點

使用vs簡單實作socket網絡通信

使用vs簡單實作socket網絡通信

最近一直在學習.Net,剛把winform基礎學習完,這次算是一個學習小結,覺得這個socket的蠻有意思的,就認真自己就完成了一遍,能簡單的發送消息,傳送檔案。窗體控件我就不一一說明了,下面直接上代碼
           

sever端代碼

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _01Sever
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket socketListen;
        private void buttonListen_Click(object sender, EventArgs e)
        {
            //當開始監聽的時候 在伺服器端建立一個負監聽責IP位址跟端口号的Socket
            socketListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //生成監聽ip位址
            IPAddress ip = IPAddress.Any;
            //建立端口号對象
            IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(textPort.Text));
            //監聽
            socketListen.Bind(point);
            ShowMessage("監聽成功");
            //設定監聽隊列
            socketListen.Listen(10);

            //建立新的線程
            Thread thread = new Thread(Watch);
            thread.IsBackground = true;
            thread.Start(socketListen);

        }
        void ShowMessage(string str)
        {
            //使用追加文本
            textLog.AppendText(str + "\r\n");
        }
        Socket socketSend;
        //根據ip找socket
        Dictionary<string, Socket> kv = new Dictionary<string, Socket>();
        void Watch(object o)
        {
            //轉換類型
            Socket socketListen = o as Socket;

            while (true)
            {
                try
                {
                    //等待用戶端的連接配接,并且建立一個負責通信的socket
                    socketSend = socketListen.Accept();
                    //将遠端連接配接的用戶端的IP位址和socket存入kv鍵值對集合中
                    kv.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                    //将遠端連接配接的用戶端的IP位址存入下拉框中
                    comboBoxIP.Items.Add(socketSend.RemoteEndPoint.ToString());
                    //擷取遠端ip位址展示連接配接成功
                    ShowMessage(socketSend.RemoteEndPoint.ToString() + ":連接配接成功");
                    //comboBoxIP
                    //用戶端連接配接成功後,伺服器應該接受用戶端發來的消息
                    //建立新的線程
                    Thread thread = new Thread(Receive);
                    thread.IsBackground = true;
                    thread.Start(socketSend);
                }
                catch { }
            }


        }
        /// <summary>
        /// 伺服器端不停的接收,用戶端發來的消息
        /// </summary>
        void Receive(object o)
        {
            Socket socketSend = o as Socket;

            //用戶端連接配接成功後,伺服器應該不停的接受用戶端發來的消息
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    //r表示實際接受的位元組數
                    int r = socketSend.Receive(buffer);
                    //關閉用戶端停止接受
                    if (r == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, r);
                    ShowMessage(socketSend.RemoteEndPoint + ":" + str);
                }
                catch { }
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        /// <summary>
        /// 服務端發送消息給用戶端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSendMessage_Click(object sender, EventArgs e)
        {
            byte[] buffer = new byte[1024 * 1024 * 2];
            buffer = Encoding.UTF8.GetBytes(textBoxMsg.Text);
            List<byte> list = new List<byte>();
            //增加标記位0表示文字
            list.Add(0);
            list.AddRange(buffer);
            byte[] newBuffer = list.ToArray();
            //向指定的用戶端發消息
            string str = comboBoxIP.SelectedItem.ToString();
            kv[str].Send(newBuffer);
            //socketSend.Send(buffer);
            textBoxMsg.Clear();
        }

        /// <summary>
        /// 選擇要發送的檔案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonOption_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "請選擇要發送的檔案";
            openFileDialog.InitialDirectory =@"C:\Users\l\Desktop";
            openFileDialog.Filter = "所有檔案|*.*";
            openFileDialog.ShowDialog();
            textBoxFile.Text = openFileDialog.FileName;
           

        }
        /// <summary>
        /// 發送檔案,首先建立檔案流讀取檔案,轉化為位元組,再使用負責通信的socket的檔案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSendFiles_Click(object sender, EventArgs e)
        {
            
            using (FileStream fileRead = new FileStream(textBoxFile.Text, FileMode.OpenOrCreate, FileAccess.Read))
            {
                byte[] buffer = new byte[1024 * 1024 * 5];
                int r = fileRead.Read(buffer,0,buffer.Length);
                List<byte> list = new List<byte>();
                list.Add(1);
                list.AddRange(buffer);
                byte[] newBuffer = list.ToArray();
                kv[comboBoxIP.SelectedItem.ToString()].Send(newBuffer, 0, r + 1,SocketFlags.None);
            }
            
            
            
        }

        private void buttonWong_Click(object sender, EventArgs e)
        {
            byte[] buffer = new byte[] { 2 };
            kv[comboBoxIP.SelectedItem.ToString()].Send(buffer);
        }
    }
}

           

Client段代碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _02Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket socketSend;
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            try
            {
                //建立負責通信的socket
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //将ip位址轉化為IPAddress對象
                IPAddress iP = IPAddress.Parse(textBoxIP.Text);
                IPEndPoint point = new IPEndPoint(iP, Convert.ToInt32(textBoxPort.Text));
                //獲得要連結的遠端伺服器的一個用程式的IP位址和端口号
                socketSend.Connect(point);
                ShowMessage("連接配接成功");
                //連接配接成功後,建立新的線程,用戶端不停的接受服務端發送的消息
                //Receive()
                Thread thread = new Thread(Receive);
                thread.IsBackground = true;
                thread.Start(socketSend);
            }
            catch { }
        }
        /// <summary>
        /// 連接配接成功後,不停的接收服務端發送的消息
        /// </summary>
        void Receive(object o)
        {
            Socket socketSend = o as Socket;

            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    //實際接受的位元組數
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    if (buffer[0] == 0)
                    {

                        string str = Encoding.UTF8.GetString(buffer, 1, r - 1);
                        ShowMessage(socketSend.RemoteEndPoint + ":" + str);
                    }
                    else if (buffer[0] == 1)
                    {
                        SaveFileDialog saveFileDialog = new SaveFileDialog();
                        saveFileDialog.Title = "請選擇儲存的位置";
                        saveFileDialog.InitialDirectory = @"C:\Users\l\Desktop";
                        saveFileDialog.Filter = "所有檔案|*.*";
                        saveFileDialog.ShowDialog(this);
                        //獲得檔案的儲存路徑
                        string path = saveFileDialog.FileName;
                        using (FileStream fileWtrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            fileWtrite.Write(buffer, 1, r - 1);
                        }
                        MessageBox.Show("儲存成功");
                    }
                    else if (buffer[0] == 2)
                    {
                        int x = this.Location.X;
                        int y = this.Location.Y;
                        ZD(x,y);
                    }
                }
                catch { }

            }

        }

        private void ZD(int x ,int y)
        {
            for (int i = 0; i < 1000; i++)
            {
                this.Location = new Point(x + 20, y + 20);
                this.Location = new Point(x - 20, y + 20);
            }
        }

        void ShowMessage(string str)
        {
            textBoxMessage.AppendText(str + "\r\n");
        }
        /// <summary>
        /// 用戶端發送資訊給服務端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSendMsg_Click(object sender, EventArgs e)
        {
            byte[] buffer = new byte[1024 * 1024 * 2];
            buffer = Encoding.UTF8.GetBytes(textBoxSendMsg.Text);
            socketSend.Send(buffer);
            textBoxSendMsg.Clear();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }
    }
}

           

繼續閱讀