简单的SOcket传送文件字符串实现

注:(程序中设置只能上传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
            {
           
            }
        }
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值