博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
文件接收网络对讲机C#服务器 Android客户端(二) C#服务器代码分析
阅读量:4959 次
发布时间:2019-06-12

本文共 9098 字,大约阅读时间需要 30 分钟。

最近研究文件接收,稍微总结一下,以后继承补充:

    

    

    :http://download.csdn.net/detail/zhujinghao09/5313666 

    序程功能绍介:

                      服务器: PC

                           言语   C#

                           按钮开启serverSocket

private void btnStartServer_Click(object sender, EventArgs e)        {            string strip = tbIP.Text;                  //手动填写IP址地            string strport = tbPort.Text;              //端口号               IPAddress IP;             int Port;             try             {                 if (strip != "" && strport != "")                 {                     IP = IPAddress.Parse(strip);                     Port = Convert.ToInt32(strport);                     this.lIP.Text = IP.ToString();                     this.lport.Text = strport;                 }                 else                               //如果没有填写任何信息,则认默是当地址地和1234端口号                       {                     IP = GetIP();                  //取得当地IP址地                        Port = 1234;                     this.lIP.Text = IP.ToString();                     this.lport.Text = Port.ToString();                 }                 if (IP != null)                     serverFullAddr = new IPEndPoint(IP, Port);                 else                 {                     MessageBox.Show("没有到得确正IP址地!!");                     return;                 }                 server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                               server.Bind(serverFullAddr);                 lbserverState.Text = "服务器已启动!!";             }             catch(Exception el)             {                 MessageBox.Show(el.Message);                 return;             }            //开启带有参数的听监线程,并把服务器socket传递给线程                 ParameterizedThreadStart parstart = new ParameterizedThreadStart(ConnectListen);            Thread thListen = new Thread(parstart);            threadList.Add(thListen);            thListen.Start((object)server);        }

               

    取得 当地IP址地            此段代码直接从网上找到的

               

public IPAddress GetIP()        {           // string strAddr = "";            IPAddress IP=null;            try            {                string strHostName = System.Net.Dns.GetHostName();                System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);                foreach (IPAddress _ipaddress in ipEntry.AddressList)                {                    if (_ipaddress.AddressFamily.ToString().ToLower() == "internetwork")                    {                        //strAddr = _ipaddress.ToString();                        IP = _ipaddress;                        break;                    }                }              //  Log.Debug("  IP:" + strAddr);            }            catch (System.Exception e)            {                //Log.Error("  Get IP Address Error:" + e.Message);                MessageBox.Show("没有取得主机的IP!!!");            }            return IP;        }

               

    听监客户端接连线程

              

private void ConnectListen(object server)        {            Socket serverSocket = (Socket)server;            while (true)                          //环循接听接连            {                serverSocket.Listen(20);                Socket acceptSock = serverSocket.Accept();                byte[] byteArray = new byte[50];                acceptSock.Receive(byteArray);//接收数据                             //接收客户端发送来过的用户名 认默50个字节,处置到得字符串                //将字节数组转成字符串                string strRec = System.Text.Encoding.Default.GetString(byteArray);     //C# byte[] 转换为  string                 string socketName = strRec.Substring(0, strRec.IndexOf("\n"));                IPAddress clientIp = ((System.Net.IPEndPoint)acceptSock.RemoteEndPoint).Address;      取得客户端IP址地                string strip = clientIp.ToString();                socketNameList.Add(socketName);                socketIpList.Add(strip);                UpdatePersonListBox();                      //更新用户列表                clientSocketList.Add(acceptSock);                ParameterizedThreadStart parstart = new ParameterizedThreadStart(RecvFile);              为每一个客户端添加接收信息听监线程                Thread th = new Thread(parstart);                threadList.Add(th);                th.Start((object)acceptSock);            }        }

               

  接收文件线程

                  

    每日一道理
喜欢海,不管湛蓝或是光灿,不管平静或是波涛汹涌,那起伏荡漾的,那丝丝的波动;喜欢听海的音声,不管是浪击礁石,或是浪涛翻滚,那轻柔的,那澎湃的;喜欢看海,不管心情是舒畅的或是沉闷的,不管天气是晴朗的或是阴沉的,那舒心的,那松弛的……
private void RecvFile(object acceptSock)        {            bool flag = false;            Socket recvSocket = (Socket)acceptSock;            byte[] byteArry = new byte[256];            string path = "recvVoice";          //建创接收文件文件夹            if (!Directory.Exists(path))            {                Directory.CreateDirectory(path);            }            string strnow = DateTime.Now.ToString("yyyyMMdd-hh-mm-ss");               //根据统系时光定名接收文件            string strpath = "recvVoice\\" + strnow + ".wav";                  byte[] buffLen = new byte[50];            int count=recvSocket.Receive(buffLen);                                  //接收文件的字节长度用于断判接收文件结束   认默50字节发送            string strRec = System.Text.Encoding.Default.GetString(buffLen);            string fLen = strRec.Substring(0, strRec.IndexOf("\n"));            int fileLen = 0;            try            {                fileLen = Convert.ToInt32(fLen);            }            catch(Exception el)            {                MessageBox.Show(el.Message);            }            int recCount = 0;            int readLen = 0;            MemoryStream memStream = new MemoryStream();            try            {                while ((recCount = recvSocket.Receive(byteArry)) > 0)                // 环循接收文件  字节发送                {                    readLen = readLen + recCount;                    if (readLen >= fileLen)                                     //跳出环循志标                         {                        memStream.Write(byteArry, 0, recCount);                        flag = true;                        break;                    }                    memStream.Write(byteArry, 0, recCount);                        //把网络流写进文件流                         flag = true;                                                  //接收文件志标                }            }            catch (Exception el)            {                flag = false;                memStream.Close();             //   fs.Close();                memStream = null;              //  fs = null;                MessageBox.Show(el.Message);                RecvFile(acceptSock);                                //应用递归  继承听监文件接收来信                return;            }            if (flag)            {                FileStream fs = new FileStream(strpath, FileMode.OpenOrCreate);                memStream.WriteTo(fs);                fs.Close();                fs = null;                 UpdateLabel(flag);                IPAddress clientIp = ((System.Net.IPEndPoint)recvSocket.RemoteEndPoint).Address;                string strip = clientIp.ToString();                int index = socketIpList.IndexOf(strip);                AddVoiceToListBox(socketNameList[index] + "****" + socketIpList[index], strpath, flag);              //把客户端用户名址地,接收文件的存保径路                                                                                                                     //添加到音声列表        }            flag = false;            memStream.Close();            memStream = null;            RecvFile(acceptSock);                                   //应用递归  继承听监文件接收来信                                          }

            

    当地音声发送数函

              

private void SendFile(Socket acceptSock,string vpath)        {            Socket sendSocket = (Socket)acceptSock;            byte[] byteArray = new byte[100];            Stream st = File.OpenRead(vpath);            Byte[] b = new Byte[1024];            string strlen = st.Length.ToString();            byte[] bytes = System.Text.Encoding.Default.GetBytes(strlen + "\r\n");          //string 转换byte[]               sendSocket.Send(bytes);             //发送文件长度     用于断判文件接收结束            int count = 0;            int sent = 0;            int offset = 0;            int left = 0;            Thread.Sleep(1000);           //重点哦            while (offset < st.Length)            {                //buffer.CopyTo(b, 1024);                count = st.Read(b, 0, 1024);                offset = offset + count;                left = Convert.ToInt32(st.Length) - offset;                if (left <= 1024)                {                    byte[] temp = new byte[left];                    sent = sendSocket.Send(b);                    // Thread.Sleep(10);                    count = st.Read(b, 0, left);                    sent = sendSocket.Send(temp);                    break;                }                sent = sendSocket.Send(b);            }            IPAddress clientIp = ((System.Net.IPEndPoint)sendSocket.RemoteEndPoint).Address;            string strip = clientIp.ToString();            int index = socketIpList.IndexOf(strip);            AddVoiceToListBox("Server Send To ****" + socketNameList[index], vpath, true);        }

    

    

    :http://download.csdn.net/detail/zhujinghao09/5313666

 

文章结束给大家分享下程序员的一些笑话语录: 问:你觉得让你女朋友(或者任何一个女的)从你和李彦宏之间选一个,你觉得她会选谁?  

  答:因为李艳红这种败类,所以我没女友!

转载于:https://www.cnblogs.com/xinyuyuanm/archive/2013/04/29/3050673.html

你可能感兴趣的文章
Rails 自定义验证的错误信息
查看>>
图论(对偶图):COGS 470. [NOI2010]海拔
查看>>
第三方类AFNetworking
查看>>
Enterprise Library 2.0 -- Cryptography Application Block
查看>>
简单的发邮件功能实现
查看>>
velocity模板引擎学习(3)-异常处理
查看>>
OllyDBG 1.10
查看>>
[svc][op]杀进程
查看>>
linux安装jdk
查看>>
求1+2+3+...+n
查看>>
[EXP]Microsoft Windows CONTACT - Remote Code Execution
查看>>
【面试】MySQL 中NULL和空值的区别?
查看>>
用js判断 iPhone6 iPhone6 plus iphonex?
查看>>
NOIp2016 蚯蚓 【二叉堆/答案单调性】By cellur925
查看>>
NOIp知识集合 By cellur925
查看>>
Nginx设置日志分割方法
查看>>
教学目标的表述方式──行为目标的ABCD表述法
查看>>
交换两个变量的值的若干种方法
查看>>
CKEditor 配置
查看>>
闪烁的文字
查看>>