初级Socket 循环发送 接收

来源:互联网 发布:雅思听力知乎 编辑:程序博客网 时间:2024/05/28 09:32
   ## 建立通讯 ##    private IPAddress serverIP;    private IPEndPoint serverFullAddr;    Socket sock;//定义一个Socket类        serverIP = IPAddress.Parse(tbxIP.Text);//服务器地址

        try        {            serverFullAddr = new IPEndPoint(serverIP, int.Parse(tbxport.Text));//设置IP,端口             sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            //指定本地主机地址和端口号              sock.Connect(serverFullAddr);            tbxError.AppendText("服务器连接开启成功。。。\r\n");        }        catch (Exception ee)        {            btnConn.Enabled = true;            tbxError.AppendText("连接服务器失败。。。请仔细检查服务器是否开启,\r\n错误原因:" + ee);        }

发送string转换成byte【】并在前面加上两个字节的长度

    /// <summary>    /// 返回合并后数组    /// </summary>    /// <param name="cmd"></param>    /// <returns></returns>    public byte[] byte_cmd(string cmd)    {        byte[] byteSend = System.Text.Encoding.UTF8.GetBytes(cmd);        int leng = byteSend.Length;//长度        int shi = leng / 256;        int ge = leng % 256;        byte[] byte3 = { (byte)shi, (byte)ge };        byte[] byte1 = copybyte(byte3, byteSend);        return byte1;    }

循环接收循环发送

     /// <summary>    /// 发送数据    /// </summary>    /// <param name="TCP_ID"></param>    /// <param name="port"></param>    public string TCP_GO(byte[] cmd)    {        int cmdLength_a = cmd.Length;//要发送的长度             byte[] message = new byte[1024*4];        string mess = "";        string newmess = "";//新的接收值        int bytes = 0;        int a = 0;//记录发送的数据长度        try        {            while (true)            {                cmdLength_a = cmdLength_a - a;//发送的总字节长度减去已发送的字节长度,得到剩余的字节长度                if (cmdLength_a == 0)                {                    break;                }                byte[] netbyte_cmd = new byte[cmdLength_a];                //截取数组1.包含要复制的数据的2.复制开始处的索引,3接收数据的 Array 4 .中存储开始处的索引 5.一个 32 位整数,它表示要复制的元素数目                Array.Copy(cmd, a, netbyte_cmd, 0, cmdLength_a );                a += sock.Send(netbyte_cmd); //发送数据            }          int lengstr = 2;//字节长度为2个字节          bytes = sock.Receive(message, lengstr, 0);//接收字节长度          byte[] bytestr_1 = new byte[2];//创建长度为两个字节的的数组接收长度          Array.Copy(message, bytestr_1, 2);//把接收到的长度信息 存到新的byte数组          string bytestr = byteToHexStr(bytestr_1);//转十六进制          int newlenth = Int32.Parse(bytestr, System.Globalization.NumberStyles.HexNumber);//转十进制 得到长度          int ANSlength = 0;//接收的数据记录          while (true)          {              newlenth =newlenth- ANSlength;//总数减去已经接收的字节长度等于剩余的字节长度              if (newlenth == 0)              {                  break;              }              ANSlength += sock.Receive(message, newlenth, 0);//再次接收全部数据              newmess += Encoding.Default.GetString(message, 0, newlenth);//追加文本          }            }        catch (Exception ex)        {            MessageBox.Show(ex.ToString());            tbxError.AppendText("出现错误,请联系管理员\r\n错误原因:" + ex.ToString());        }        return newmess;

}

关闭连接

 try        {              sock.Close();              tbxError.AppendText("服务器连接关闭成功。。。\r\n");        }        catch (Exception ex)        {              tbxError.AppendText("服务器连接关闭失败。。。\r\n错误原因:" + ex.ToString());        }
原创粉丝点击