天天看点

使用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;
        }
    }
}

           

继续阅读