c# c/s结构Socket上传文件的代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c# c/s结构Socket上传文件的代码相关的知识,希望对你有一定的参考价值。

我没接触过socket编程,谁能该我一份c#的,c/s结构的上传文件的代码,通过桌面上传给服务器,谢谢啦
仅需要c# socket上传图片文件的简单代码,最好是两个函数(上传和下载)就可以了,我没接触过这个,我现在只需要实现该功能就可以了,我也不懂的怎么用流来写,希望最好写个实例代码,多谢了

    发送端(client)

    private void button2_Click(object sender, EventArgs e)
           
              
                this.button2.Enabled = false;
                Thread TempThread = new Thread(new ThreadStart(this.StartSend));
                TempThread.Start();
               
           

            private void StartSend()
           
                //FileInfo EzoneFile = new FileInfo(this.textBox1.Text);

                string path = @"E:\\old F directory\\TangWei\\kangge\\new1.jpg";

                FileInfo EzoneFile = new FileInfo(path);

                FileStream EzoneStream = EzoneFile.OpenRead();

                int PacketSize = 100000;

                int PacketCount = (int)(EzoneStream.Length / ((long)PacketSize));

            //    this.textBox8.Text = PacketCount.ToString();

            //    this.progressBar1.Maximum = PacketCount;

                int LastDataPacket = (int)(EzoneStream.Length - ((long)(PacketSize * PacketCount)));

           //    this.textBox9.Text = LastDataPacket.ToString();
                IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("163.180.117.229"), 7000);

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

                client.Connect(ipep);

       //         TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(EzoneFile.Name));

       //         TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketSize.ToString()));

        //        TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketCount.ToString()));

        //        TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(LastDataPacket.ToString()));

                byte[] data = new byte[PacketSize];

                for(int i=0; i<PacketCount; i++)
               
                    EzoneStream.Read(data, 0, data.Length);

                    TransferFiles.SendVarData(client, data);

       //             this.textBox10.Text = ((int)(i + 1)).ToString();

       //             this.progressBar1.PerformStep();
               

                if(LastDataPacket != 0)
               
                    data = new byte[LastDataPacket];

                    EzoneStream.Read(data, 0, data.Length);

                    TransferFiles.SendVarData(client,data);

        //            this.progressBar1.Value = this.progressBar1.Maximum;
               
                client.Close();

                EzoneStream.Close();

                this.button2.Enabled = true;
           

    接收端  (server)

           private void button2_Click(object sender, EventArgs e)
           
                //int i = 0;
                //FileStream recfs = new FileStream("E:\\\\kangge.jpg", FileMode.OpenOrCreate);
                //Byte[] recbyte = new Byte[2000000];
                //Socket hostsocket = receive.Accept();
                //BinaryWriter newfilestr = new BinaryWriter(recfs);
                //hostsocket.Receive(recbyte, recbyte.Length, SocketFlags.None);
                //for (i = 0; i < recbyte.Length; i++)
                //
                //    newfilestr.Write(recbyte, i, 1);
                //
                //recfs.Close();

                //hostsocket.Shutdown(SocketShutdown.Receive);
                //hostsocket.Close();

                this.button2.Enabled = false;
                Thread TempThread = new Thread(new ThreadStart(this.StartReceive));
                TempThread.Start();
               
           
            private void StartReceive()
           
                IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("163.180.117.229"), 7000);

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

                server.Bind(ipep);

                server.Listen(10);

                Socket client = server.Accept();

         //       IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;

          //      string SendFileName = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));

           //     string BagSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));

          //      int bagCount = int.Parse(System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)));

          //      string bagLast = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
                int file_name = 1;

                string fileaddr = "E:\\\\old F directory\\\\TangWei\\\\Copy of kangge\\\\" + file_name.ToString() + ".jpg";
               
                FileStream MyFileStream = new FileStream(fileaddr, FileMode.Create, FileAccess.Write);

        //        int SendedCount = 0;

                while(true)
               
                    byte[] data = TransferFiles.ReceiveVarData(client);
                    if(data.Length == 0)
                   
                        break;
                   
                    else
                   
                       // SendedCount++;
                        MyFileStream.Write(data, 0, data.Length);
                   
               

                MyFileStream.Close();

                client.Close();

              this.button2.Enabled = true;
           

    公共类。 TransferFiles

        class TransferFiles
       

            public TransferFiles()
           

           

            public static int SendVarData(Socket s, byte[] data) // return integer indicate how many data sent.
           
                int total = 0;
                int size = data.Length;
                int dataleft = size;
                int sent;
                byte[] datasize = new byte[4];
                datasize = BitConverter.GetBytes(size);
                sent = s.Send(datasize);//send the size of data array.

                while (total < size)
               
                    sent = s.Send(data, total, dataleft, SocketFlags.None);
                    total += sent;
                    dataleft -= sent;
               

                return total;
           

            public static byte[] ReceiveVarData(Socket s) // return array that store the received data.
           
                int total = 0;
                int recv;
                byte[] datasize = new byte[4];
                recv = s.Receive(datasize, 0, 4, SocketFlags.None);//receive the size of data array for initialize a array.
                int size = BitConverter.ToInt32(datasize, 0);
                int dataleft = size;
                byte[] data = new byte[size];

                while (total < size)
               
                    recv = s.Receive(data, total, dataleft, SocketFlags.None);
                    if (recv == 0)
                   
                        data = null;
                        break;
                   
                    total += recv;
                    dataleft -= recv;
               

                return data;

           
       

     

参考技术A 以流的形式写
int port = 1234;

int port = 1234;
IPAddress ip = IPAddress.Parse("127.0.0.1");
socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(ip,port);
//socket.Blocking = false;
socket.Bind(iep);
socket.Listen(10);
Console.WriteLine("start......");
try

for (int i = 0; i < 10;i++ )




catch

Console.WriteLine("异常!");
socket.Close();


接收端
private void Receive(Socket socket)

NetworkStream ns = new NetworkStream(socket);
FileStream fs = new FileStream("c:\\file.txt", FileMode.OpenOrCreate);
bool isRead = true;
while (isRead)

int count = ns.Read(this._receiveBuf, 0, this._receiveBuf.Length);
int datanum = 0;
datanum = BitConverter.ToInt32(this._receiveBuf, 0); //从buffer中的前4个字节读出count
if (datanum > 0) //确定每次要接受多少字节数

fs.Write(this._receiveBuf, 4, datanum);

else //如果接受字节数为0 就推出

isRead = false;


this.txtFile.Text = "文件传输成功";
fs.Close();

---------------------
发送端
private void btSend_Click(object sender, System.EventArgs e)

if (this._isConnect)

_ns = _tc.GetStream();
string path = this.txtPath.Text.Trim();
FileStream fs = new FileStream(path, FileMode.Open);
int sendCount = 0;
byte[] countbuffer = null;
byte[] clientbuffer = new byte[1004];
while (sendCount < fs.Length && _ns.CanWrite)

int count = fs.Read(_sendBuf, 0, _sendBuf.Length); //读出要发送的数据
countbuffer = BitConverter.GetBytes(count);
countbuffer.CopyTo(clientbuffer,0);
_sendBuf.CopyTo(clientbuffer, 4);
this._ns.Write(clientbuffer, 0, 4 + count); //写入网络流
sendCount += count;

countbuffer = BitConverter.GetBytes(0); //发送完文件后 发送count = 0
this._ns.Write(countbuffer, 0, countbuffer.Length); //使接收端停止
_ns.Close();
fs.Close();



http://hi.baidu.com/lqj1112/blog/item/9a0fd21638c6461e962b4336.html

http://topic.csdn.net/u/20080514/23/23e325fc-7040-4c0b-bb6c-d1223704397c.html本回答被提问者采纳
参考技术B String server = "210.34.213.74";;
Int32 port = 9900;
TcpClient tc = new TcpClient();
tc.Connect(server,port);
String file = @"c:\1.doc";
FileStream fs = File.Open(file,FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] bt = new byte[(int)fs.Length];
br.Read(bt, 0, bt.Length);
NetworkStream ns = tc.GetStream();
ns.Write(bt, 0, bt.Length);

byte[] receive = new byte[1024];
ns.Read(receive, 0, receive.Length);
String res = System.Text.Encoding.BigEndianUnicode.GetString(receive);
if (res == "ok")



else


tc.Client.Close();
tc.Close();
简单的是这样,发文件好说,关键在于服务器端的解析.

C# Winform 多线程 SOCKET 文件上传,下载

一个S, 服务器端
N个C,客户端

上传
S随时监听端口,C发来上传文件请求后开始接收文件,如果网络中断,下次C再连接的时候,可以支持上一次文件断点续传

下载
S随时监听端口,C发来下载文件请求后开始发送文件,如果网络中断,下次C再连接的时候,可以支持上一次文件断点续传

参考技术A 这可是很麻烦的,自己到网上找吧 参考技术B 文件数据流传输方法,自己定义握手协议就可以实现,底层SOCKET的代码网上多的是本回答被提问者和网友采纳 参考技术C 这个很麻烦的网上找一下教程吧。 参考技术D 服务器保存上传的每个(未完成)文件信息(如:已上传的流的位置)及特定的文件标识,客户端保存未完成(下载)的文件信息及特定标识;每次上传或下载文件时将相关信息写入协议中,传送到对方,对方解析后再进行数据传输。
如果客户端较多的话,可以考虑客户端先连接到服务器,再由服务器进行反连接。这样不会阻塞服务器的监听。

以上是关于c# c/s结构Socket上传文件的代码的主要内容,如果未能解决你的问题,请参考以下文章

C#谁能给我个,C/S 通过Socket与线程通信的例子,,

c#C/S实现文件的上传下载

linux socket c/s上传文件

C# winform 中C/S结构,客户端怎么获取截屏,获取图片,把图片保存到服务器图片文件夹里面?

c#在winform的C/S结构下,如何使用工作流实现业务流程审核、方案审批等!急!

c# c/s 之间如何做心跳检测