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

我没接触过socket编程,谁能该我一份c#的,c/s结构的上传文件的代码,通过桌面上传给服务器,谢谢啦仅需要c#socket上传图片文件的简单代码,最好是两个函数(上传... 我没接触过socket编程,谁能该我一份c#的,c/s结构的上传文件的代码,通过桌面上传给服务器,谢谢啦
仅需要c# socket上传图片文件的简单代码,最好是两个函数(上传和下载)就可以了,我没接触过这个,我现在只需要实现该功能就可以了,我也不懂的怎么用流来写,希望最好写个实例代码,多谢了
展开
 我来答
dong_1984dd
2015-08-25 · TA获得超过1.1万个赞
知道小有建树答主
回答量:1070
采纳率:100%
帮助的人:229万
展开全部
  1. 发送端(client)

  2. 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;
            }

  3. 接收端  (server)

  4.        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;
            }

  5. 公共类。 TransferFiles

  6.     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;

            }
        }

  7.  

mj390
2009-07-30 · TA获得超过262个赞
知道小有建树答主
回答量:225
采纳率:0%
帮助的人:231万
展开全部
以流的形式写
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
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
azur2000
2009-07-30 · TA获得超过321个赞
知道小有建树答主
回答量:315
采纳率:0%
帮助的人:220万
展开全部
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();
简单的是这样,发文件好说,关键在于服务器端的解析.
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(1)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式