陋室铭
永远也不要停下学习的脚步(大道至简至易)

posts - 2169,comments - 570,views - 413万

注:(程序中设置只能上传jpg格式文件,可以传其它类型文件)


服务器
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace WindowsApplication1
{
    public partial class FormReceive2 : Form
    {
        public FormReceive2()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 得到本机IP
        /// </summary>
        /// <returns></returns>
        public IPAddress GetServerIP()
        {
            IPHostEntry ieh = Dns.GetHostByName(Dns.GetHostName());
            return ieh.AddressList[0];
        }

        /// <summary>
        /// 接收文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void receiveFile()
        {
            Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ///设置接收数据的地址
            IPAddress ServerIp = GetServerIP();
            IPEndPoint hostPoint = new IPEndPoint(ServerIp, 8000);

            ///设置端口
            receiveSocket.Bind(hostPoint);
            ///监听
            Start:
            receiveSocket.Listen(2);

            ///设置接收数据缓冲区的大小
            Byte[] recData = new Byte[100000];
            Socket hostSocket = receiveSocket.Accept();
            ///接收数据
            int i = 0;
            int bytes = 0;
            ///创建一个新文件保存接收的数据
            string ImagePicture = "E:\\" + Convert.ToString(Guid.NewGuid()) + ".jpg";
            FileStream fileStream = new FileStream(ImagePicture, FileMode.OpenOrCreate);
            BinaryWriter writer = new BinaryWriter(fileStream);
            while (true)
            {
                bytes = hostSocket.Receive(recData, recData.Length, 0);
                //读取完成后退出循环 
                i += bytes;
                if (bytes <= 0)
                    break;
                writer.Write(recData, 0, bytes);
            }
            //将读取的字节数转换为字符串    
            if (i > 0)
            {
                ///显示接收数据的信息
                label1.Text = "网页在" + DateTime.Now.ToString() + "接收的数据大小为:" + i.ToString();
            }

            ///关闭写文件流
            fileStream.Close();
            writer.Close();

            ///关闭接收数据的Socket
            hostSocket.Shutdown(SocketShutdown.Receive);
            hostSocket.Close();
            goto Start;
        }
        /// <summary>
        /// 接收字符
        /// </summary>
        private void receiveWord()
        {
            Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ///设置接收数据的地址
            IPAddress ServerIp = GetServerIP();
            IPEndPoint hostPoint = new IPEndPoint(ServerIp, 8001);

            ///设置端口
            receiveSocket.Bind(hostPoint);
            ///监听
            Start:
            receiveSocket.Listen(2);

            ///设置接收数据缓冲区的大小
            Byte[] recData = new Byte[100000];
            Socket hostSocket = receiveSocket.Accept();

            string recvStr = "";
            int bytes = 0;
            while (true)
            {

                bytes = hostSocket.Receive(recData, recData.Length, 0);
                //读取完成后退出循环    
                if (bytes <= 0)
                    break;
                //将读取的字节数转换为字符串    
                recvStr += Encoding.UTF8.GetString(recData, 0, bytes).TrimEnd().TrimStart();
            }
            recvStr = "来自IP和端口" + hostSocket.RemoteEndPoint.ToString() + "的信息" + recvStr;
            MessageBox.Show(recvStr);
            ///关闭接收数据的Socket
            hostSocket.Shutdown(SocketShutdown.Receive);
            hostSocket.Close();
            goto Start;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            receiveFile();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            receiveWord();
        }

        /// <summary>
        /// 改变Byte[]长度
        /// </summary>
        /// <param name="array"></param>
        /// <param name="newSize"></param>
        /// <returns></returns>
        private Byte[] Resize(Byte[] array, int newSize)
        {
            Byte[] newArray = new Byte[newSize];
            array.CopyTo(newArray, 0);
            return newArray;
        }
    }
}






客户端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace WindowsApplication1
{
    public partial class FormSend2 : Form
    {
        public FormSend2()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 发送文件
        /// </summary>
        private void SocketSendFile()
        {
            ///创建发送数据的Socket
            Socket sendsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ///设置发送数据的地址
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.0.21"), 8000);
            ///创建读取文件的流
            if (openFileDialog1.FileName == "openFileDialog1")
            {
                MessageBox.Show("请先选择图片");
            }
            else
            {
                FileStream fileSteam = new FileStream(openFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.Read);
                ///文件大小
                Byte[] fsSize = new Byte[fileSteam.Length - 1];
                ///读取文件的二进制流
                BinaryReader reader = new BinaryReader(fileSteam);

                ///读取数据
                reader.Read(fsSize, 0, (int)fileSteam.Length - 1);
                ///链接目的地
                try
                {
                    sendsocket.Connect(endPoint);
                }
                catch
                {
                    MessageBox.Show("不能连接到服务器");
                    return;
                }
                ///发送数据
                try
                {
                    sendsocket.Send(fsSize);
                }
                catch
                {
                    MessageBox.Show("服务器忙,请稍后再发!");
                }

                ///关闭文件流
                fileSteam.Close();
                ///关闭发送数据的Socket
                sendsocket.Shutdown(SocketShutdown.Send);
                sendsocket.Close();
            }
        }

        /// <summary>
        /// 发送字符
        /// </summary>
        private void SocketSendWord()
        {
            ///创建发送数据的Socket
            Socket sendsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ///设置发送数据的地址
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.0.21"), 8000);
            int iLength = textBox1.Text.Length;
            //获取要发送的数据的长度
            Byte[] bySend = new byte[iLength];
            //根据获取的长度定义一个Byte类型数组
            bySend = System.Text.Encoding.UTF8.GetBytes(textBox1.Text);
            //按照指定编码类型把字符串指定到指定的Byte数组
            try
            {
                sendsocket.Connect(endPoint);
            }
            catch
            {
                MessageBox.Show("不能连接到服务器");
                return;
            }
            int i = sendsocket.Send(bySend);
            ///关闭发送数据的Socket
            sendsocket.Shutdown(SocketShutdown.Send);
            sendsocket.Close();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            SocketSendFile();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SocketSendWord();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.DefaultExt = "jpg";
            // The Filter property requires a search string after the pipe ( | )
            this.openFileDialog1.Filter = "图片文档(*.*)|*.*";
            this.openFileDialog1.ShowDialog();
            try
            {
                int j = openFileDialog1.FileName.LastIndexOf(".");
                string ExtendName = openFileDialog1.FileName.Substring(j);
                if (ExtendName == ".jpg" || ExtendName == ".JPG")
                {
                    if (this.openFileDialog1.FileNames.Length > 0)
                    {
                        foreach (string filename in this.openFileDialog1.FileNames)
                        {
                            int a = filename.LastIndexOf("\\");
                            string strPath = filename.Substring(a, filename.Length - a);

                            Image ImagePicture = Image.FromFile(strPath);
                            this.pictureBox1.Image = ImagePicture;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("只能上传jpg格式文件!");
                    return;
                }
            }
            catch
            {
           
            }
        }
    }
}

 

 

posted on   宏宇  阅读(5380)  评论(2编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
< 2007年2月 >
28 29 30 31 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 1 2 3
4 5 6 7 8 9 10

点击右上角即可分享
微信分享提示